Skip to content
Related Articles

Related Articles

vector emplace() function in C++ STL
  • Difficulty Level : Basic
  • Last Updated : 09 Jul, 2018

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:

  • position – It specifies the iterator pointing to the position in the container where the new element is to be inserted.
  • args – It specifies the element to be inserted to be inserted in the vector container.

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

Below programs illustrates the above function:



Program 1:




// 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;
}


Output:

The vector elements are: 15 10 20 30

Program 2:




// 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;
}


Output:

The vector elements are: 10 20 30 16

Program 3:




// 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;
}


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.

My Personal Notes arrow_drop_up
Recommended Articles
Page :