I am trying to write a data structure that I can cycle round, sort of a circular list, using a vector. I resize which I am thinking should initialise the underlying array with ten elements. I don’t understand why I cannot advance the iterator. Can someone please help.
I cannot use push_back() because that will always append to the end which is not what I want.
// 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;
}
EDIT
Changed loop to this:
for(int i = 0; i < 100; ++i) {
if(it == myvec.end())
it = myvec.begin();
*it++ = i;
}
I didn’t properly understand insert.
From what you expect in output – I believe you misunderstood what
insertis doing.Implement your loop in this way (without insering – just replacing).
std::vector<>::insertincrements the size of your vector by one – I believe it is not what you expect.Do not do this:
But this:
Then you’ll get your desired ouput: