vector iterators c++

vector iterators c++

本文关键字:c++ iterators vector      更新时间:2023-10-16

我对开始和结束工作的方式有点困惑,他们似乎对我不一致。当向前和向后移动时,它们有不同的行为。

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()指向向量的第一个元素,但end()指向经过最后一个元素。取消对end()的引用永远不安全,但可以将迭代器与它进行比较。

如果向量为空,则为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)来代替。

应该使用反向迭代器:

int y = 0;
while(a.rbegin() +y != a.rend()){
    cout << (*(a.rbegin()+y)) << "n";
    y++;
}

或者更好的是使用迭代器本身的重载++操作符:

auto iter = a.rbegin();
while(iter != a.rend()){
    cout << *(iter++) << "n";
}

一个非常简单的实现方法是执行

// first element to the last
auto it = a.begin()
while (it != a.end())
{
cout<<*it<<"n";
++it;
}
cout<<"n"
// Last element to first
auto rit = a.rbegin()
while(rit != a.rend())
{
cout<<*rit<<"n";
++rit;
}

注意:不要试图解引用a.p end()及以后的对象。当程序中的y = 0cout << (*(a.end()-y)) << "n";行中解引用a.d end()时,会导致段错误。vector的元素包含在一个可以从begin()end()-1访问的序列中,.end()指向容器最后一个元素的"后面",不应该被解引用。

std::for_each(a.begin(), a.end(), [](const Actor *& a){ std::cout << a; });
std::for_each(a.rbegin(), a.rend(), [](const Actor *& a){ std::cout << a; });

auto print_actor = [](const Actor *& a){ std::cout << a; };
std::for_each(a.begin(), a.end(), print_actor);
std::for_each(a.rbegin(), a.rend(), print_actor);