Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

add a new item to vector and shift it remaining part to right

Tags:

c++

I am trying to put a new item to vector, and shift remaining items. How can I do that ?

Ex

vector -------------------------------------------------------
       | 1 | 2 | 3 | 4 | 5 | 9 | 10 | 15 | 21 | 34 | 56 | 99 |
       -------------------------------------------------------
                                      ^
new item = 14, it should be added to  ^

After insertion, 


vector ------------------------------------------------------------
       | 1 | 2 | 3 | 4 | 5 | 9 | 10 | 14 | 15 | 21 | 34 | 56 | 99 |
       ------------------------------------------------------------
                                         ^                         ^
                                         ^-shifted to right by one-^
like image 927
compi Avatar asked Feb 21 '23 15:02

compi


2 Answers

Check the vector::insert() function.

vector<int> vec ;

// Add elements to vec
vec.insert(vec.begin() + position, new_item);
like image 135
vz0 Avatar answered Feb 23 '23 05:02

vz0


Use insert.

vector<int> v {1,2,3,5};
v.insert (v.begin() + 3, 4); //v is now {1,2,3,4,5}

You can also insert ranges of elements and other cool stuff, similar to the vector constructor.

like image 34
chris Avatar answered Feb 23 '23 05:02

chris