Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Adding to middle of std::vector

Tags:

c++

string

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.

like image 465
calccrypto Avatar asked Jan 26 '11 01:01

calccrypto


People also ask

How do you add elements to the middle of a vector?

Elements can be added in the middle of a Vector by using the java. util. Vector. insertElementAt() method.

How do you add an element to a vector in C++?

To add elements to vector, you can use push_back() function. push_back() function adds the element at the end of this vector. Thus, it increases the size of vector by one.

Can you add to a vector?

A variety of mathematical operations can be performed with and upon vectors. One such operation is the addition of vectors. Two vectors can be added together to determine the result (or resultant).

How do you add elements to a vector array?

The vector::insert() function in C++ Basically, the vector::insert() function from the STL in C++ is used to insert elements or values into a vector container. In general, the function returns an iterator pointing to the first of the inserted elements.


1 Answers

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.

like image 125
templatetypedef Avatar answered Oct 04 '22 00:10

templatetypedef