[英]vector iterator in c++
我正在尝试使用迭代器在C ++中遍历vector<char*>
。 我已经建立一个应该在端部开始,和向后步骤(朝向开始,或虚设程序rend()
上的数> 0,并转发(朝向端部,或rbegin()
上的数)< 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;
}
谁能找出问题所在?
编辑
我忘了我做了些小改动。 我以前的代码没有在初始化for循环中填充tmp
。 已经修复
问题是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;
}
由于目标实际上是不使用过去的位置,因此我重述了这个问题:它需要两个迭代器,一个指向所需范围内的第一个元素,另一个指向最后一个。 然后,机制变得简单:
if (it != end)
++it;
cout << *it << endl;
同样,朝另一个方向:
if (it != begin)
--it;
cout << *it << endl;
起点和终点的定义如下:
typedef vector<char*>::reverse_iterator iter;
iter begin = vect.rbegin();
iter end = --vect.rend(); // assumes that vect is not empty
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.