#include#include int main() { std::set mySet; mySet.insert(2); mySet.insert(8); mySet.insert(4); for (auto& element : mySet) { std::cout << element << ' '; } // Output: 2 4 8 return 0; }
#include#include bool compare(int a, int b) { return a > b; } int main() { std::set mySet(compare); mySet.insert(2); mySet.insert(8); mySet.insert(4); for (auto& element : mySet) { std::cout << element << ' '; } // Output: 8 4 2 return 0; }
#includeThe C++ object set is part of the Standard Template Library (STL) in C++ and comes pre-installed with any C++ compiler.#include #include class Person { public: std::string name; int age; Person(std::string name, int age) : name(name), age(age) {} }; struct CompareByAge { bool operator()(const Person& a, const Person& b) const { return a.age < b.age; } }; int main() { std::set people; people.insert(Person("Alice", 25)); people.insert(Person("Bob", 35)); people.insert(Person("Charlie", 20)); for (auto& person : people) { std::cout << person.name << " (" << person.age << ")" << std::endl; } /* Output: Charlie (20) Alice (25) Bob (35) */ return 0; }