1

我正在尝试编写一个可以循环使用的数据结构,类似于循环列表,使用向量。我调整了我认为应该用十个元素初始化底层数组的大小。我不明白为什么我不能推进迭代器。有人可以帮忙吗。

我不能使用 push_back() ,因为它总是会附加到末尾,这不是我想要的。

// re-use start of vector when get to end
#include <vector>
#include <iostream>
#include <algorithm>

using std::cout;
using std::endl;
using std::vector;

class printme {
public:
   void operator() (int val) {cout << val << endl; }
};


//get a debug assertion - message says: vector iterators incompatible
//I assume this means that it is invalid after previous it++
int main(int argc, char* argv[])
{
   vector<int> myvec;
   myvec.resize(10);  //underlying array now has size=10 elements
   vector<int>::iterator it = myvec.begin();  //point to start of array
   for(int i = 0; i < 100; ++i) {
      if(it == myvec.end())           //on 2nd iteration crashes here - invalid iterator
         it = myvec.begin();

      myvec.insert(it++, i);
   }

   //print contents of vector - check 90-99 printed
   for_each(myvec.begin(), myvec.end(), printme());

    return 0;
}

编辑将循环更改为:

for(int i = 0; i < 100; ++i) {
   if(it == myvec.end())
      it = myvec.begin();

   *it++ = i;
}

我没有正确理解插入。

4

2 回答 2

1

根据您对输出的期望 - 我相信您误解了insert正在做的事情。以这种方式实现你的循环(不插入 - 只是替换)。std::vector<>::insert将向量的大小增加一 - 我相信这不是您所期望的。

不要这样做:

myvec.insert(it++, i);

但是这个:

 *it++ = i;

然后你会得到你想要的输出:

   //print contents of vector - check 90-99 printed
   for_each(myvec.begin(), myvec.end(), printme());
于 2012-10-16T11:26:02.667 回答
0

Iterators can be invalidated by some operations on a vector - including insert. You'll need to re-fectch it in order to be able to use it after the insert.

vector<int>::iterator it = myvec.begin();  //point to start of array
for(int i = 0; i < 100; ++i) {
   if(it == myvec.end())           //on 2nd iteration crashes here - invalid iterator
       it = myvec.begin();

   myvec.insert(it++, i);
   //it can be invalid here, re-fetch it
   it = myvec.begin();
}
于 2012-10-16T11:08:42.753 回答