c++ - vector 迭代器 C++

标签 c++ pointers vector iterator

我对开始和结束工作的方式感到有点困惑,它们在我看来似乎是不一致的。前进和后退时,他们有不同的行为。

vector<Actor *> a;
a.push_back(new Actor(11));
a.push_back(new Actor(22));
a.push_back(new Actor(33));
vector<Actor *>::iterator it = a.begin();


int x  =0;
while(a.begin()+x != a.end()){
cout << (*(a.begin()+x)) << "\n";
x++;
}

cout << "\n";

int y = 1; // if this is set to 0 then its a seg fault =/ when I access 
while(a.end()-y != a.begin()){
cout << (*(a.end()-y)) << "\n";
y++;
}

输出

0x979a008
0x979a028
0x979a018


0
0x979a018
0x979a028

我怎样才能得到预期的模式

0x979a008
0x979a028
0x979a018

0x979a018
0x979a028
0x979a008

最佳答案

请注意,begin() 指向 vector 的第一个元素,但 end() 指向最后一个元素之后。取消引用 end() 是不安全的,但您可以将迭代器与它进行比较。

如果 vector 为空,则 begin() == end(),您不能取消引用任何一个。

循环 vector 元素的更惯用的方法是:

for (vector<Actor*>::iterator i = a.begin(); i != a.end(); ++i) {
   // do something here
}

要反向迭代,使用 rbegin()rend() 更简单,它们的工作方式与 begin()/end(),但以相反的顺序迭代:

for (vector<Actor*>::reverse_iterator i = a.rbegin(); i != a.rend(); ++i) {
   // do something here
}

此外,如果您不打算修改元素,则应使用 const_iterator(或 const_reverse_iterator)。

关于c++ - vector 迭代器 C++,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15540095/

相关文章:

image - OpenCV 图像矩阵到向量到矩阵

performance - 迭代 State Monad 并以良好的性能按顺序收集结果

C++ 文件选择窗口

c++ - 将 char 绑定(bind)到枚举类型

c - 你如何在c中返回一个指向不可修改数据的指针

pointers - 在 Python 中访问 memoryview 类型的数据缓冲区

c++ - 将 vector 的迭代器发送到函数中。 (C++)

c++ - 无法在 vs2012 中构建任何 c++ 项目。错误 LNK1327 : rc. exe

c++ - 从基础创建派生结构

python - ctypes:将指向 char 的指针分解/转换为指向 char 的指针数组