Appearance
Not quite equal, but emplace_back() can be better in certain situations. Let me explain the differences:
Key Differences
push_back(): Takes an object and copies/moves it into the vector
cpp
vector<pair<int,int>> v;
v.push_back(make_pair(1, 2)); // Creates pair, then moves it
v.push_back({1, 2}); // Creates pair, then moves itemplace_back(): Constructs the object directly in the vector using the arguments you provide
cpp
vector<pair<int,int>> v;
v.emplace_back(1, 2); // Constructs pair directly in vectorPerformance Comparison
For simple types (int, long long, etc.): No difference
cpp
vector<int> v;
v.push_back(5); // Same performance
v.emplace_back(5); // Same performanceFor complex types with expensive constructors: emplace_back() is potentially faster
cpp
vector<string> v;
v.push_back(string(1000, 'a')); // Creates temp string, then moves
v.emplace_back(1000, 'a'); // Constructs directly, no tempFor pairs/tuples: emplace_back() is cleaner
cpp
vector<pair<int,int>> v;
v.push_back({1, 2}); // OK but creates temporary
v.emplace_back(1, 2); // Better, direct constructionWhen to Use What?
- Competitive programming: Use
emplace_back()for pairs/tuples (cleaner syntax), either for simple types - Already have an object: Use
push_back(obj) - Want to construct in-place: Use
emplace_back(args...)
In practice for CP, the performance difference is negligible for most cases, but emplace_back() gives cleaner code when working with pairs and complex structures!