我尝试使用递归函数输出int型向量的所有参数,它工作,但在图像描述这里有一个调试断言失败发生。 请帮我指出问题出在哪里。 提前谢谢你。
#include<iostream>
#include<vector>
using namespace std;
void val(vector<int>::const_iterator beg, vector<int>::const_iterator end)
{
if (beg!=end)
cout << *beg << endl;
val((beg + 1),end);
}
int main()
{
int n;
vector<int> vec;
while (cin >> n)
vec.push_back(n);
val(vec.begin(),vec.end());
}
几乎是对的,但是当你到达向量的末尾时,不要用递归的方式来称呼你自己
void val(vector<int>::const_iterator beg, vector<int>::const_iterator end)
{
if (beg!=end)
{
cout << *beg << endl;
val((beg + 1),end);
}
}
您还没有提供递归应该停止的位置。 您可以使用如下所示的内容
void val(vector<int>::const_iterator beg, vector<int>::const_iterator end)
{
if(beg == end) return;
cout << *beg << endl;
val(beg + 1,end);
}