In this C++ tutorial, you shall learn how to insert an element at the beginning of a vector using vector::insert() function, with example programs.

Insert Element at Beginning of Vector

To append/insert an element at the beginning of a vector in C++, we can use vector::insert() method. Call insert() method on the vector, and pass the vector’s begin() and the element as arguments. The method inserts/appends the element at the beginning of the vector.

The syntax of the statement to insert an element e at the beginning of the vector v is

v.insert(v.begin(), e);

C++ Program

In the following program, we take a vector of strings in fruits, and insert an element "apple" at the beginning of the vector fruits.

main.cpp

#include <iostream>
#include <vector>
using namespace std;

int main() {
   vector<string> fruits { "banana", "cherry", "mango" };
   
   fruits.insert(fruits.begin(), "apple");
   
   for(auto& element: fruits) {
      cout << element << endl;
   }
}

Output

apple
banana
cherry
mango
ADVERTISEMENT

Conclusion

In this C++ Tutorial, we learned how to insert an element at the beginning of a vector, using vector::insert() method.