vector insert() in C++

insert(): It is a build-in function in STL. It inserts the given value into a vector before 

specified iterator.

It returns an iterator that points to the inserted data. This function will insert a copy of the given value

before the specified location. 

Note that this kind of operation could be expensive for a vector.

Parameters: 

position: A const_iterator into the vector.

data: Data to be inserted. 

Syntax:

vecName.insert(position, data) 

For Example:

vec = {1,3,4,5}

vec.insert(vec.begin()+1,2) = > It insert 2 after first element of the vector.

So, vector becomes (i.e vec = {1,2,3,4,5})

Approach

C++

#include <bits/stdc++.h>
using namespace std;

int main()
{
    vector<intvec = {1345};

    //insert element after first element
    //of the vector
    vec.insert(vec.begin() + 12);

    for (int i = 0i < vec.size(); i++)
        cout << vec[i] << " ";

    return 0;
}


No comments:

Post a Comment