How to add elements in the "x" position of a std :: vector

4

How do I add an element to the position I indicate in std::vector ? Not to delete what you already have, but is to add in the middle. Here's an example:

Let's suppose that within std::vector has the elements

{1,2,3,4,5,6,7,8,9};

And I want to add a number before 4 and after 3, but without deleting any element, thus:

{1,2,3,10,4,5,6,7,8,9}

How to proceed? Is this possible? Or do I need to use some other container , like list ?

    
asked by anonymous 30.01.2016 / 14:20

2 answers

2

You can use the insert() method, but you need to create an iterator:

#include <iostream>
#include <vector>

int main () {
    std::vector<int> vec {1, 2, 3, 4, 5, 6, 7, 8, 9};
    auto it = vec.begin();
    vec.insert(it + 3, 10);
    for (auto x: vec) {
         std::cout << ' ' << x;
    }
}

See running on ideone .

If you do it correctly, measure it and the performance does not please you, then you need to use another structure that has other commitments. list may be an option. It can do insertion in the middle with complexity O (1). But other operations are not as fast as vector . Do not fix one thing and break another. See what is priority. Perhaps another structure is more appropriate. There is no perfect structure where everything is great.

    
30.01.2016 / 14:37
0

The insert method exists exactly for this. It inserts the element in a certain position and drags the rest of the vector forward. You can do this: YourVetor.insert (YourVetor.begin () + position, YourVetor [position]).

    
30.01.2016 / 14:36