Why do the overloads of vector::insert return void?
template <class InputIterator>
void insert ( iterator position, InputIterator first, InputIterato开发者_如何转开发r last );
I need to insert twice into my vector, but the data is large and my vector needs to reallocate. How am I supposed to know where to insert the second time (at the same position) if the call to insert
invalidates the iterator?
Am I supposed to do something like this:
int offset = position - vector.begin();
vector.insert(position, data.begin(), data.end());
vector.insert(vector.begin() + offset, moredata.begin(), moredata.end());
It just seems there is a better way.
Er... But you are the only person that knows where you want to insert your data. How is vector supposed to know where you are planning to make the second insertion?
If you plan to make two consecutive insertions at the same location (just guessing), then you can convert your iterator to "reallocation-independent" form (index), and then convert it back to iterator after the first insertion.
In C++0x, the range insertion overload of insert
returns an iterator, just as the single-element insertion overload does.
template <class InputIterator>
iterator insert(const_iterator position,
InputIterator first, InputIterator last);
You would need to obtain a new iterator and go from there.
There is a version of insert that does not return void. Check here.
精彩评论