How do I use emplace vs push with std::set?

In C++, the `std::set` container allows the storage of unique elements in a specific order. When adding elements to a `std::set`, you can use either `emplace` or `insert` (often confused with `push` in other containers). The choice between these two methods can impact the performance of your code depending on the context.

Using Emplace vs Insert with std::set

The `insert` method adds copies or moves of the object to the set. In contrast, `emplace` constructs the object in place and can be more efficient as it avoids unnecessary copies.

Example of using emplace vs insert

#include <set> #include <iostream> struct MyStruct { int value; MyStruct(int v) : value(v) {} bool operator<(const MyStruct &other) const { return value < other.value; } }; int main() { std::set mySet; // Using insert (might involve copy) mySet.insert(MyStruct(1)); // Using emplace (constructs in place) mySet.emplace(2); for (const auto& elem : mySet) { std::cout << elem.value << std::endl; } return 0; }

std::set emplace insert C++ performance coding unique elements STL