C++ set for user defined data type?



A set is a data structure that is used to store distinct values (meaning no two elements can have the same value) in ascending or descending order.

Set for User-defined Data Types

We can directly use sets for built-in data types, but for user-defined data types, values cannot be directly stored, because a set compares the elements to maintain order, but for user-defined data types such as array or struct, the compiler will not be able to perform a comparison between them. The set container is defined under the <set> header file.

So to use user-defined datatypes into a stack, we have to override < operator or custom comparator, which will compare two values of that type such as for set, map etc.

Syntax

Here is the following syntax of overloaded < operator inside the class/struct for set data structure.

struct structName { // member variables will be defined here bool operator<(const structName& other) const { // comparison logic will be implemented here and return the result in bool } }; set<structName> mySet;

Here is the following syntax of using a custom comparator for struct for set data structure.

struct structName { // member variables will be defined here }; struct Comparator { bool operator()(const structName& a, const structName& b) const { // comparison logic will be implemented here and return the result in bool } }; set<structName, Comparator> mySet;

Example of Set for User-defined Data Types

Here is the following example program, showcasing how the set is used with struct to store a person object in a set with sorted elements, first by age and then by name using a custom comparator.

Open Compiler
#include <iostream> #include <set> using namespace std; struct person { string name; int age; }; // here is the custom comparator to sort persons by age and then by name struct personCompare { bool operator()(const person& a, const person& b) const { if (a.age != b.age) return a.age < b.age; return a.name < b.name; } }; int main() { set<person, personCompare> people; // we can't add duplicates in set people.insert({"Aman", 30}); people.insert({"Bob", 25}); people.insert({"Alex", 30}); people.insert({"Ashi", 30}); for (const auto& p : people) { cout << p.name << " (" << p.age << ")\n"; } return 0; }

Output

Bob (25)
Alex (30)
Aman (30)
Ashi (30)
Akansha Kumari
Akansha Kumari

Hi, I am Akansha, a Technical Content Engineer with a passion for simplifying complex tech concepts.

Updated on: 2025-05-29T18:57:55+05:30

472 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements