Sitemap
Vidhi koul

Vidhi koul

๐—•๐—ฎ๐˜๐˜๐—น๐—ฒ ๐—ผ๐—ณ ๐—ฆ๐—ง๐—Ÿ: ๐—ฝ๐˜‚๐˜€๐—ต_๐—ฏ๐—ฎ๐—ฐ๐—ธ ๐˜ƒ๐˜€ ๐—ฒ๐—บ๐—ฝ๐—น๐—ฎ๐—ฐ๐—ฒ_๐—ฏ๐—ฎ๐—ฐ๐—ธ โ€” ๐—ช๐—ต๐—ผโ€™๐˜€ ๐—™๐—ฎ๐˜€๐˜๐—ฒ๐—ฟ?

2 min readSep 14, 2025

--

Press enter or click to view image in full size
push_back VS emplace_back

C++ STL is full of little optimisations that can make a huge difference in performance when dealing with large datasets. One such pair of functions that often causes confusion is push_back vs emplace_back.

Letโ€™s break it down in simple terms.

The Basics

  • push_back โ†’ Adds an element to the end of a container by copying or moving it.
  • emplace_back โ†’ Constructs the element directly at the end of the container (in-place construction).

Example:

#include <bits/stdc++.h>
using namespace std;
struct Student {
string name;
int age;
Student(string n, int a) : name(n), age(a) {
cout << "Constructor called for " << name << endl;
}
Student(const Student& s) {
cout << "Copy constructor called for " << s.name << endl;
}
};
int main() {
vector<Student> students;

cout << "--- Using push_back ---" << endl;
students.push_back(Student("Gita", 21));

cout << "--- Using emplace_back ---" << endl;
students.emplace_back("Sita", 20);
}

Output:

--- Using push_back ---
Constructor called for Gita
Copy constructor called for Gita
--- Using emplace_back ---
Constructor called for Sita

Notice the difference:

  • With push_back, the object is constructed outside and then copied/moved inside the vector.
  • With emplace_back, it is constructed directly inside the vector โ†’ avoiding the extra copy.

When to Use What?

  • Use emplace_back when you are creating an object directly in the container.
  • Use push_back when you already have an object created.

Example:

Student s("Ram", 22);
students.push_back(s); // Correct
students.emplace_back(s); // Not efficient here

Performance Impact

For lightweight objects like integers or chars โ†’ negligible difference.
For complex objects (like classes with expensive constructors, strings, pairs, or nested containers) โ†’ emplace_back gives a significant performance boost.

Takeaway

emplace_back is not just syntactic sugar. It allows direct in-place construction, reducing unnecessary copies or moves, making your code both faster and cleaner.

Get Vidhi koulโ€™s stories inย yourย inbox

Join Medium for free to get updates fromย thisย writer.

๐Ÿ‘‰ Rule of thumb:

  • If constructing on the fly โ†’ use emplace_back.
  • If you already have the object โ†’ use push_back.

โšก Small change, big impact. Thatโ€™s the beauty of C++!

--

--