vector emplace() function in C++ STL

The vector::emplace() is an STL in C++ which extends container by inserting new element at position. Reallocation happens only if there is a need of more space. Here the container size increases by one.

Syntax:

template 
iterator vector_name.emplace (const_iterator position, element);

Parameter:
The function accepts two mandatory parameters which are specified as below:

Return value: The function returns an iterator which points to the newly inserted element.

Below programs illustrates the above function:



Program 1:

filter_none

edit
close

play_arrow

link
brightness_4
code

// C++ program to illustrate the
// vector::emplace() function
// insertion at thefront
#include <bits/stdc++.h>
using namespace std;
  
int main()
{
    vector<int> vec = { 10, 20, 30 };
  
    // insert element by emplace function
    // at front
    auto it = vec.emplace(vec.begin(), 15);
  
    // print the elements of the vector
cout << "The vector elements are: "
    for (auto it = vec.begin(); it != vec.end(); ++it)
        cout << *it << " ";
  
    return 0;
}
chevron_right

Output:
The vector elements are: 15 10 20 30

Program 2:

filter_none

edit
close

play_arrow

link
brightness_4
code

// C++ program to illustrate the
// vector::emplace() function
// insertion at the end
#include <bits/stdc++.h>
using namespace std;
  
int main()
{
    vector<int> vec = { 10, 20, 30 };
  
    // insert element by emplace function
    // at the end
    auto it = vec.emplace(vec.end(), 16);
  
    // print the elements of the vector
cout << "The vector elements are: "
    for (auto it = vec.begin(); it != vec.end(); ++it)
        cout << *it << " ";
  
    return 0;
}
chevron_right

Output:
The vector elements are: 10 20 30 16

Program 3:

filter_none

edit
close

play_arrow

link
brightness_4
code

// C++ program to illustrate the
// vector::emplace() function
// insertion at the middle
#include <bits/stdc++.h>
using namespace std;
  
int main()
{
    vector<int> vec = { 10, 20, 30 };
  
    // insert element by emplace function
    // in the middle
    auto it = vec.emplace(vec.begin() + 2, 16);
  
    // print the elements of the vector
cout << "The vector elements are: "
    for (auto it = vec.begin(); it != vec.end(); ++it)
        cout << *it << " ";
  
    return 0;
}
chevron_right

Output:
The vector elements are: 10 20 16 30

Attention reader! Don’t stop learning now. Get hold of all the important C++ Foundation and STL concepts with the C++ Foundation and STL courses at a student-friendly price and become industry ready.

Article Tags :
C++
Practice Tags :