emplace_back method in C++ explanation with example

emplace_back method in C++ explanation with example:

emplace_back is a public member function in std::vector. This method is used to insert one new element to the end of a vector.

In this post, we will learn how to use emplace_back method with examples.

What is emplace_back:

emplace_back is used to insert an element at the end of a vector, after the current last element. This is constructed and placed at the end. This construction is in-place.

It is defined as below:

void emplace_back (Args&&... args);

Here, args is the arguments to construct the new element.

The arguments should be of same type. Else, it will throw an error.

Example program:

Let’s try with an example:

#include <vector>
#include <iostream>
using namespace std;
  
int main()
{
    vector<int> intArray;

    intArray.emplace_back(1);
    intArray.emplace_back(0);
    intArray.emplace_back(1);
    intArray.emplace_back(0);
    intArray.emplace_back(1);
  
    for (auto& it : intArray) {
        cout << it << ' ';
    }
    return 0;
}

It will print:

1 0 1 0 1

Example 2: emplace_back with a vector holding strings:

emplace_back works in a similar way with a vector holding strings. For example:

#include <vector>
#include <iostream>
using namespace std;
  
int main()
{
    vector<string> strArray;

    strArray.emplace_back("Hello");
    strArray.emplace_back("World");
  
    for (auto& it : strArray) {
        cout << it << ' ';
    }
    return 0;
}

It will print:

Hello World 

You might also like: