calccrypto
calccrypto

Reputation: 8991

Adding to middle of std::vector

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.

Upvotes: 14

Views: 30825

Answers (3)

in this example dynamically find the vector middle and insert new element.

std::vector <std::string> friends;

friends.push_back("Ali");
friends.push_back("Kemal");
friends.push_back("Akin");
friends.push_back("Veli");
friends.push_back("Hakan");
    
// finding middle using size() / 2
int middleIndexRef = friends.size() / 2;

friends.insert(friends.begin() + middleIndexRef, "Bob");

Upvotes: 0

Walter Mundt
Walter Mundt

Reputation: 25271

You can do that, but it will be really slow:

int split = 3; // where to split
a.insert(a.begin()+index, a[index].substr(0, split));
a[index+1] = a[index+1].substr(split);

Upvotes: 2

templatetypedef
templatetypedef

Reputation: 372764

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.

Upvotes: 21

Related Questions