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-^
Check the vector::insert() function.
vector<int> vec ;
// Add elements to vec
vec.insert(vec.begin() + position, new_item);
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With