c++ – How to add elements at "x" position of a std::vector


How to proceed to add an element in the position that I indicate in a std::vector ? It's not to delete what you already have, but to add in the middle. Here's an example:

Let's suppose that inside a std::vector it has the elements


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


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


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 it working on ideone . And on repl.it. I also put it on GitHub for future reference .

If you do it correctly, measure and the performance doesn't please, then you need to use another framework that has other compromises. A list may be an option. It can do middle insertion with O(1) complexity. But other operations are not as fast as the vector . Don't fix one thing and break another. See what's a priority. Maybe another structure is more suitable. There is no perfect structure where everything is great.

Scroll to Top