vector insert() function in C++ STL



vector insert() function in C++ STL helps to increase the size of a container by inserting the new elements before the elements at the specified position.

It is a predefined function in C++ STL.

We can insert values with three types of syntaxes

1. Insert values by mentioning only the position and value:

vector_name.insert(pos,value);

2. Insert values by mentioning the position, value and the size:

vector_name.insert(pos,size,value);

3. Insert values in another empty vector form a filled vector by mentioning the position, where the values are to be inserted and iterators of filled vector:

empty_eector_name.insert(pos,iterator1,iterator2);

Algorithm

Begin    Declare a vector v with values.    Declare another empty vector v1.    Declare another vector iter as iterator.    Insert a value in v vector before the beginning.    Insert another value with mentioning its size before the beginning.    Print the values of v vector.    Insert all values of v vector in v1 vector with mentioning the iterator of v vector.    Print the values of v1 vector. End.

Example

 Live Demo

#include<iostream> #include <bits/stdc++.h> using namespace std; int main() {    vector<int> v = { 50,60,70,80,90},v1;        //declaring v(with values), v1 as vector.    vector<int>::iterator iter;                  //declaring an iterator    iter = v.insert(v.begin(), 40);              //inserting a value in v vector before the beginning.    iter = v.insert(v.begin(), 1, 30);           //inserting a value with its size in v vector before the beginning.    cout << "The vector1 elements are: \n";    for (iter = v.begin(); iter != v.end(); ++iter)       cout << *iter << " "<<endl;             // printing the values of v vector    v1.insert(v1.begin(), v.begin(), v.end()); //inserting all values of v in v1 vector.    cout << "The vector2 elements are: \n";    for (iter = v1.begin(); iter != v1.end(); ++iter)       cout << *iter << " "<<endl;            // printing the values of v1 vector    return 0; }

Output

The vector1 elements are: 30 40 50 60 70 80 90 The vector2 elements are: 30 40 50 60 70 80 90
Updated on: 2019-07-30T22:30:25+05:30

806 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements