I need to insert values into the beginning of a std::vector
and I need other values in this vector to be pushed to further positions for example: something added to beginning of a vector and values moved from position 1 to 2, from 2 to 3 etc.
How can I do that?
It works alot like a std::vector but you can add and remove items from both the front and the end. It does this by dividing the internal storage up into smaller blocks.
To add elements to vector, you can use push_back() function. push_back() function adds the element at the end of this vector. Thus, it increases the size of vector by one.
vector::begin() begin() function is used to return an iterator pointing to the first element of the vector container. begin() function returns a bidirectional iterator to the first element of the container.
Use the std::vector::insert function accepting an iterator to the first element as a target position (iterator before which to insert the element):
#include <vector> int main() { std::vector<int> v{ 1, 2, 3, 4, 5 }; v.insert(v.begin(), 6); }
Alternatively, append the element and perform the rotation to the right:
#include <vector> #include <algorithm> int main() { std::vector<int> v{ 1, 2, 3, 4, 5 }; v.push_back(6); std::rotate(v.rbegin(), v.rbegin() + 1, v.rend()); }
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