Re: STL vector insert/erase question
Boltar <boltar2003@yahoo.co.uk> wrote in news:4b6c3d17-cf41-4860-bee0-
b91dc43b8bfb@i12g2000prf.googlegroups.com:
Hi
Is there a way of inserting and erasing to/from a vector using an
array index instead of an iterator or alternatively a way to map an
index number to an iterator?
Sure. The general pattern to convert an index to an iterator is to add
begin() to the index. That is....
iterator it = v.begin() + index;
Of course, you have to do your own bounds checking.
eg:
vector<int> v;
v.push_back(123);
v.push_back(789);
v.insert(1,456);
This would be:
v.insert(v.begin() + 1, 456);
printf("%d\n",v[1]);
v.erase(1)
This would be:
v.erase(v.begin() + 1);
So the above would print 456 but 789 would now be at index 2. Then it
would delete 789.
Sorry if this is a dummies question.
B2003
Generally speaking, the index functions of vector are just convenience
functions. The api is really more attuned to iterator use and you
should probably just get used to using iterators instead of indexes for
most things. Having said that, I realize that there are legitimate
needs for index based uses of vectors, but most of the time, iterators
work just as well and the methodology is portable between container
types.
joe