C++ .emplace()

MakrisCharalampos's avatar
Published Aug 24, 2024
Contribute to Docs

The .emplace() function is a member of the std::vector class in C++. It allows for the direct construction of an element within the vector at a specified position. Introduced in C++11, .emplace() enhances performance by avoiding unnecessary copying of elements.

  • Looking for an introduction to the theory behind programming? Master Python while learning data structures, algorithms, and more!
    • Includes 6 Courses
    • With Professional Certification
    • Beginner Friendly.
      75 hours
  • Learn C++ — a versatile programming language that’s important for developing software, games, databases, and more.
    • Beginner Friendly.
      11 hours

Syntax

vector.emplace(position, Args&&... args);
  • position: An iterator to the position before which the new element will be inserted.
  • args...: The arguments used to directly construct the new element within the vector.

Example

In the example below, an object of MyClass is directly constructed at the beginning of the vector using .emplace() with the arguments 10 and 20. This function enhances efficiency by constructing the object in place, eliminating the need for any unnecessary temporary object creation.

#include <iostream>
#include <vector>
class MyClass {
public:
// Constructor that takes two integers x and y
MyClass(int x, int y) : x(x), y(y) {
std::cout << "MyClass constructed with x=" << x << " and y=" << y << std::endl;
}
private:
int x, y;
};
int main() {
std::vector<MyClass> myVector;
// Use emplace() to directly construct a MyClass object in place at the beginning of the vector
// This will call the MyClass constructor with the arguments 10 and 20
myVector.emplace(myVector.begin(), 10, 20);
return 0;
}

The above code produces the output as follows:

MyClass constructed with x=10 and y=20

All contributors

Contribute to Docs

Learn C++ on Codecademy

  • Looking for an introduction to the theory behind programming? Master Python while learning data structures, algorithms, and more!
    • Includes 6 Courses
    • With Professional Certification
    • Beginner Friendly.
      75 hours
  • Learn C++ — a versatile programming language that’s important for developing software, games, databases, and more.
    • Beginner Friendly.
      11 hours