Junior — Middle
What type of data or objects are permissible to store inside a std::set container in C++?
sobes.tech AI
Answer from AI
Any data types for which the less-than operator (<) is defined can be stored in a std::set container in C++, as std::set stores elements in sorted order and uses this operator for ordering.
These can include:
- Primitive types (int, double, char, etc.)
- User-defined classes and structures, if they have a defined < operator or a comparator is provided when creating the set
Example with a user-defined type:
#include <set>
#include <string>
struct Person {
std::string name;
int age;
bool operator<(const Person& other) const {
return age < other.age; // sorting by age
}
};
int main() {
std::set<Person> people;
people.insert({"Alice", 30});
people.insert({"Bob", 25});
}
If the < operator is not defined, compilation will fail.