a shot of dev knowledge

RELATED TAGS

What is std::vector::insert() in C++?

The insert() function is defined in the <vector> header and is used to add an element or elements into a vector.

The function can be used in three main ways, as discussed below.

1. Single element

Prototype

iterator insert(iterator position, const value_type& val);

Syntax

myVector.insert(position, val)

Arguments

  • position: an iterator that points to the position where the value is to be added.
  • val: the single element that needs to be added at position.
#include <iostream>
#include <vector>
using namespace std;

int main()
{
  vector<int> vec;

  vector<int>::iterator iter = vec.begin();

  iter = vec.insert(iter, 1);
  iter = vec.insert(iter, 2);

  int vecSize = vec.size();

  cout << vecSize << endl;

  for(int i = 0; i < 2; i++)
  {
    cout << vec.at(i) << " ";
  }

  cout << endl;

  return 0;
}

2. Fill

Prototype

void insert(iterator position, size_type n, const value_type& val);

Syntax

myVector.insert(position, size, val)

Arguments

  1. position: an iterator that points to the position where the value is to be added.

  2. size: the number of times the element is added.

  3. val: the single element that needs to be added at position.

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

int main()
{
  //decleration of int vector
  vector<int> vec;

  vec.insert(vec.end(), 1, 1);
  vec.insert(vec.end(), 2, 2);
  vec.insert(vec.end(), 3, 3);

  int vecSize = vec.size();

  cout << vecSize << endl;

  for(int i = 0; i < vecSize; i++)
  {
    cout << vec.at(i) << " ";
  }

  cout << endl;

  return 0;
}

3. Range

In this syntax, we can add elements from one vector into another.

Prototype

void insert(iterator position, InputIterator first, InputIterator last);

Syntax

myVector.insert(position, iter1, iter2)

Arguments

  1. position: an iterator that points to the position where the value is to be added.

  2. iter1: starting position of the elements that need to be added.

  3. iter2: ending position of the elements that need to be added.

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

int main()
{
  vector<int> vec1 = {0, 1, 2, 3};
  vector<int> vec2;

  vec2.insert(vec2.begin(), vec1.begin(), vec1.end());

  int vec2Size = vec2.size();

  cout << vec2Size << endl;

  for(int i = 0; i < vec2Size; i++)
  {
    cout << vec2.at(i) << " ";
  }

  cout << endl;

  return 0;
}

Return value

Every syntax returns an iterator that points to the newly inserted element or the first of the newly inserted elements.

RELATED TAGS

RELATED COURSES

View all Courses

Keep Exploring