Re: Question about STL Vector design
On 2007-10-12 19:55, chsalvia@gmail.com wrote:
I have a question about the design of STL vector. One thing I wonder
was why the STL designers chose to have the insert() and erase()
functions take an iterator as the first argument, rather than simply
an array index integer referring to a position in the array.
Probably since all the STL containers and algorithms operate on
iterators, it would be a shame to leave vector out of all the good stuff
that the other containers enjoy.
The reason I wonder this is because firstly, the implementation will
need to convert the iterator to an array index integer anyway, because
the iterator may become invalidated if a reallocation occurs, and
secondly, it's easier to simply type something like vec.erase(5)
rather than vec.erase(vec.begin() + 5).
First, the implementation does not have to convert it to an index, just
check if the iterator refers to the current element. And even if you
want to convert it to an index that would not be very hard. Second, the
iterator will only be invalid *after* the call to erase. Third, if you
know the index it is very easy to get an iterator to that element:
std::vector<T>::iterator it = vec.begin() + index;
I suppose the reason they did it was so that you can easily swap a
std::vector with an std::list or something else in your code without
breaking the code. But does anyone agree with me that it makes more
sense for a vector, at least, to take an array index integer rather
than iterator for erase/insert, particularly because the iterator may
become invalidated anyway after the operation?
The iterator will become invalid after the operation, always. And no it
does not make sense to make vector a special case when you can just do
vec.erase(vec.begin() + index);
to get what you want.
--
Erik Wikstr??m