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,

Download  Run Code

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:

Download  Run Code

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:

Download  Run Code

Output:

1 2 3 4 5

That’s all about inserting an element at the beginning of a vector in C++.