Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I insert element into beginning of vector?

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?

like image 792
Paweł Szymkowicz Avatar asked Jan 14 '18 15:01

Paweł Szymkowicz


People also ask

Can we add element in vector from front?

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.

How do you add an element to a vector?

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.

What is V begin () in vector?

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.


1 Answers

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()); } 
like image 58
Ron Avatar answered Oct 12 '22 22:10

Ron