C++ unordered_set emplace() Function
Example
Add "Audi" and "BMW" to an unordered set:
unordered_set<string> cars = {"Volvo", "BMW", "Ford", "Mazda"};
cars.emplace("Audi");
cars.emplace("BMW");
cout << cars.size();
Definition and Usage
The emplace() function adds a new element to an unordered set. It builds the element directly inside the unordered set.
If the value already exists, nothing is added. In the example, "Audi" is added, but "BMW" already exists. So the size is 5, not 6.
The emplace function is defined in the <unordered_set> header file.
Tip: For simple values like strings and numbers, emplace() and insert() give the same result.
Syntax
unordered_set.emplace(type value)
type is the type of the elements in the unordered set, like string in the example.
Parameter Values
| Parameter | Description |
|---|---|
| value | Required. The value of the new element. |
Technical Details
| Returns: | A pair. Its first is an iterator to the element, and its second is true if the element was added, or false if it already existed. |
|---|
Related Pages
Read more about unordered sets in our Unordered Set Tutorial.