C++ set insert() Function
Example
Add a new element to a set:
set<string> cars = {"Volvo", "BMW", "Ford", "Mazda"};
cars.insert("Tesla");
for (string car : cars) {
cout << car << "\n";
}
Definition and Usage
The insert() function adds one or more elements to a set.
A set only keeps unique values, so if the value already exists, it is not added again. The new element is placed in the correct sorted position.
The insert function is defined in the <set> header file.
Syntax
set.insert(type value)
type is the type of the elements in the set, like string in the example.
Parameter Values
| Parameter | Description |
|---|---|
| value | Required. The value to add. To add several values at once, put them inside curly braces, like {"Tesla", "Audi"}. |
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 sets in our Sets Tutorial.