ewo*_*wok 2 c++ iterator vector segmentation-fault
我试图使用迭代器来遍历vector<char*>c ++.我已经构建了一个虚拟程序,该程序应该在结束时开始,然后rend()在数字> 0的情况下向后(朝向开始,或),在数字<0上向前(向末端,或rbegin()),并在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;
}
Run Code Online (Sandbox Code Playgroud)
任何人都可以发现问题吗?
编辑
我忘记了我做了一个小改动.我之前的代码没有tmp在初始化for循环中填充.已修复
问题是rend迭代器将一个项指向序列的(反向)结束.取消引用它会导致段错误:
if (it < vect.rend()){
cout << *(++it) << endl;
} else{
cout << *it << endl; // <---- segfault
}
Run Code Online (Sandbox Code Playgroud)
最小的修复可能是
if (it+1 < vect.rend())
{
cout << *(++it) << endl;
} else{
cout << *it << endl;
}
Run Code Online (Sandbox Code Playgroud)