English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية

C++ vector emplace() usage and example

C++ Vector (Container)

Is C++ 11 A newly added member function of the standard library, used to insert a new element before the specified position in the vector container.
 Note: emplace() can only insert one element at a time, not multiple.

Syntax

The syntax of vector (vector) v is:

Iterator it = v.emplace(pos, args);

Parameters

pos: It defines the position to insert the new element.

args: Parameters passed for constructing the new element.

Return value

It returns an iterator to the newly inserted element.

Example1

Let's look at a simple example.

#include iostream>
#include<vector>
using namespace std;
int main()
{
vector<int> v{1,2,3,4,5};
cout << "The elements of vector v are:\t ";
for(int i = 0; i < v.size(); i++)
cout << v[i] << " \t ";
cout << '\n';
cout << "After adding two elements, the elements are:\t ";
vector<int>::iterator it = v.emplace(v.begin(),+2,8);
v.emplace(it,9);
for(int i = 0; i < v.size(); i++)
cout << v[i] << " \t ";
return 0;
}

Output:

The elements of vector v are:1 2 3 4 5
After adding two elements, the elements are:1 2 9 8 3 4 5

In this example, the size of the vector container is increased using the emplace() function.

Example2

Let's look at another simple example.

#include iostream>
#include<vector>
using namespace std;
int main()
{
vector<string> v{"mango","apple","banana"};
v.emplace(v.begin()}+2, "strawberry");
for(int i = 0; i < v.size(); i++)
std::cout << v[i] << " ";
return 0;
}

Output:

Mango apple strawberry banana

In this example, the size of the vector container is increased by adding a new string to the vector (vector) using the emplace() function.

C++ Vector (Container)