std::setset_name; set_name.insert(value);
#include#include int main() { std::set my_set = { 1, 2, 3, 4 }; my_set.insert(5); my_set.insert(6); my_set.insert(7); for (auto i : my_set) std::cout << i << " "; return 0; } // output: 1 2 3 4 5 6 7
#includeIn this example, we create a custom data type called `Person` that has a name and an age. We overload the less than operator so that the set can sort the elements based on age. We then create a set called `people` and insert three `Person` objects into it. Finally, we print out the elements of the set. The CPP std set insert function belongs to the C++ standard library, specifically the#include class Person { public: std::string name; int age; Person(std::string name, int age) : name(name), age(age) {} bool operator<(const Person& p) const { return this->age < p.age; } }; int main() { std::set people; people.insert({ "Bob", 25 }); people.insert({ "Alice", 27 }); people.insert({ "Charlie", 30 }); for (auto p : people) std::cout << p.name << " " << p.age << std::endl; return 0; } // output: Bob 25 // Alice 27 // Charlie 30