Insert an element at the beginning of a vector in C++
This post will discuss how to insert an element at the beginning of a vector in C++.
1. Using std::vector::insert function
The standard solution to insert an element to a vector is with the std::vector::insert function. It takes an iterator to the position where the element needs to be inserted. To insert an element at the beginning of a vector, pass an iterator pointing to the first element in the vector. For example,
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 |
#include <iostream> #include <vector> #include <iterator> int main() { std::vector<int> v = {2, 3, 4, 5}; int target = 1; // add target at beginning v.insert(v.begin(), target); // print vector std::copy(v.begin(), v.end(), std::ostream_iterator<int>(std::cout, " ")); return 0; } |
Output:
1 2 3 4 5
2. Using std::rotate function
Alternatively, we can append the element at the vector’s end and then rotate the vector to the right by 1 position. A typical implementation of this approach would look like this:
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 |
#include <iostream> #include <vector> #include <algorithm> #include <iterator> int main() { std::vector<int> v = {2, 3, 4, 5}; int target = 1; // add target at beginning v.push_back(target); std::rotate(v.rbegin(), v.rbegin() + 1, v.rend()); // print vector std::copy(v.begin(), v.end(), std::ostream_iterator<int>(std::cout, " ")); return 0; } |
Output:
1 2 3 4 5
3. Using std::deque
To add and remove elements from both the front and the end of a container, consider using a std::deque. It implements a Double-ended queue that can expand or shrink on both ends. To insert an element at the beginning, use the push_front member function of std::deque, as shown below:
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 |
#include <iostream> #include <deque> #include <iterator> int main() { std::deque<int> d = {2, 3, 4, 5}; int target = 1; // add target at beginning d.push_front(target); // print vector std::copy(d.begin(), d.end(), std::ostream_iterator<int>(std::cout, " ")); return 0; } |
Output:
1 2 3 4 5
That’s all about inserting an element at the beginning of a vector in C++.
Thanks for reading.
To share your code in the comments, please use our online compiler that supports C, C++, Java, Python, JavaScript, C#, PHP, and many more popular programming languages.
Like us? Refer us to your friends and support our growth. Happy coding :)