How to add elements at the "x" position of an Std::vector

Asked

Viewed 1,246 times

5

How to proceed to add an element at the position I specify in a std::vector? Not to delete what you already have, but to add in the middle. Here’s an example:

Let’s assume that inside a std::vector possess 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, so:

{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 the list?

2 answers

2


You can use the method insert(), 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;
}

Behold working in the ideone. And in the repl it.. Also put on the Github for future reference.

If you do it correctly, measure and the performance does not please, then you need to use another structure that has other commitments. A list can be an option. It can insert into the middle with complexity O(1). But other operations are not as fast as the 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.

  • Well, is there any other faster way to do this? Here in my program gave a lag... Obg

  • I doubt it exists, but it is not to be too slow no. I do not know how you are using, so I can not say if it is right. But if there really is a performance problem, then you have to use another data structure that allows you to enter more quickly, giving up some feature that the vector has, for example, list.

0

There is the Insert method exactly for this. It inserts the element in a given position and drags the rest of the vector forward. You can do this: Its vector.Insert(Its vector.Begin()+position, Its vector[position]).

Browser other questions tagged

You are not signed in. Login or sign up in order to post.