Alex Rivera | Logout

Adding to middle of std::vector

Asked 2011-01-26T01:40:56.820
14

Is there a way to add values to the middle of a vector in C++? Say I have:

vector <string> a;
// a gets filled up with "abcd", "wertyu", "dvcea", "eafdefef", "aeefr", etc

and I want to break up one of the strings and put all of the pieces back into the vector. How would I do that? the strings I break can be anywhere, index = 0, somewhere in the middle, or index = a.size() - 1.

Edit
Report

1 Answer

22

You can insert into a vector at position i by writing

v.insert(v.begin() + i, valueToInsert);

However, this isn't very efficient; it runs in time proportional to the number of elements after the element being inserted. If you're planning on splitting up the strings and adding them back in, you are much better off using a std::list, which supports O(1) insertion and deletion everywhere.

answered 2011-01-26T01:44:52.377

Your Answer