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

C++ vector emplace_back() Usage and Example

C++ Vector (Container)

This function is used to insert a new element at the end of the vector (vector) and increase the size of the vector (vector) container.

Syntax

The syntax for the vector (vector) 'v' is:

v.emplace_back(args);

Parameters

args: Parameters passed for constructing the new element.

Return value

It does not return any value.

Example1

Let's look at a simple example.

#include <iostream>
#include<vector>
using namespace std;
int main()
{
    vector<char> v{'C','+});
    v.emplace_back('+');
    for(int i = 0; i < v.size(); i++{
        cout << v[i];
    }
    return 0;
}

Output:

C++

In this example, the size of the vector (vector) 'v' is increased by adding a new character value at the end of the vector (vector) using the emplace_back() function.

emplace() vs insert()

The insert() function is used to copy objects into the vector (vector), while the emplace() function is only used to construct objects within the vector (vector), thus avoiding unnecessary operations.

A simple understanding is that emplace() constructs elements directly at the specified position in the container when inserting elements, rather than generating them separately and then copying (or moving) them into the container. Therefore, it is recommended to use emplace() first in practical applications.

Example2

Let's look at another simple example.

#include <iostream>
#include<vector>
using namespace std;
int main()
{
    vector<int> v{1,2,3,4,5};
    v.emplace_back(6);
    for(int i = 0; i < v.size(); i++{
        cout << v[i] << " ";
    }
    return 0;
}

Output:

1 2 3 4 5 6

In this example, the emplace_back() function is used to add a new integer value at the end of the vector (i.e., after the last element).

C++ Vector (Container)