C++ unordered_set insert() Function
Example
Add a new element to an unordered set:
unordered_set<string> cars = {"Volvo", "BMW", "Ford", "Mazda"};
cout << "Before: " << cars.size() << "\n";
cars.insert("Tesla");
cout << "After: " << cars.size();
Definition and Usage
The insert() function adds one or more elements to an unordered set.
An unordered set only keeps unique values, so if the value already exists, it is not added again.
The insert function is defined in the <unordered_set> header file.
Tip: To add several elements at once, put them in a list, like cars.insert({"Tesla", "Audi"});.
Syntax
unordered_set.insert(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 to add. |
Technical Details
| Returns: | When you add one element: 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. When you add several elements: nothing. |
|---|
Related Pages
Read more about unordered sets in our Unordered Set Tutorial.