我正在尝试使用迭代器遍历 vector<char*>
在 C++ 中。我已经构建了一个虚拟程序,它应该从末尾开始,然后在 >0 的数字上后退(向开头,或 rend()
),并在 < 0,并在 0 处退出。如果迭代器已到达任一端并且用户尝试进一步,它应该在该端重复该元素并且不移动迭代器。我的问题是,如果用户试图跑到最后,而不是这样做,我只会得到一个段错误。这是我的代码:
#include <iostream>
#include <vector>
#include <stdio.h>
using namespace std;
int main(){
vector<char*> vect;
char* tmp;
for (int i=1; i<=5; i++){
tmp = new char[7];
sprintf(tmp, "hello%d", i);
vect.push_back(tmp);
}
vector<char*>::const_reverse_iterator it = vect.rbegin();
int a;
cin >> a;
while (a!=0){
if (a>0){
if (it < vect.rend()){
cout << *(++it) << endl;
} else{
cout << *it << endl;
}
} else{
if (it > vect.rbegin()){
cout << *(--it) << endl;
} else{
cout << *it << endl;
}
}
cin >> a;
}
return 0;
}
谁能找出问题所在?
编辑
我忘了我做了一个小改动。我以前的代码没有填充 rbegin()
在初始化for循环中。已修复
最佳答案
问题在于 rend
迭代器将一项指向序列的(反向)末端。取消引用它会导致段错误:
if (it < vect.rend()){
cout << *(++it) << endl;
} else{
cout << *it << endl; // <---- segfault
}
一个最小的修复可能是
if (it+1 < vect.rend())
{
cout << *(++it) << endl;
} else{
cout << *it << endl;
}
关于c++ - C++中的 vector 迭代器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11936754/