Skip to content
Related Articles

Related Articles

C++ set for user define data type
  • Difficulty Level : Medium
  • Last Updated : 19 Apr, 2018

The C++ STL set is a data structure used to store the distinct value in ascending or descending order. By default, we can use it to store system defined data type only(eg. int, float, double, pair etc.).

And if we want to store user-defined datatype in a set (eg. structure) then the compiler will show an error message. That is because of the property of the set that value kept in the set must be ascending or descending order. And while doing so the compiler cant compare two structures(as they are user-defined) and that’s the reason to why the compiler shows us the error message.
So, in order to store a structure in a set, some comparison function need s to be designed. Implementation of this is given below:

Examples:

Input  : 110 102 101 115
Output : 101 102 110 115

Explanation:
Here we insert a random list to the set, and when we output the set the list gets sorted in ascending order based on the comparison function we made.

Input  : 3  2  34   0 76 
Output : 0  2   3  34 76




// CPP implementation to use 
// user-defined data type in
// structures
#include<bits/stdc++.h>
using namespace std;
  
// Structure definition
struct Test {
    int id;
      
    // This function is used by set to order
    // elements of Test.
    bool operator<(const Test& t) const
    {
        return (this->id < t.id);
    }
};
  
// Driver method
int main()
{
    // put values in each 
    // structure define below.
    Test t1 = { 110 }, t2 = { 102 }, 
         t3 = { 101 }, t4 = { 115 };
  
    // define a set having 
    // structure as its elements.
    set<struct Test> s; 
      
    // insert structure in set
    s.insert(t1); 
    s.insert(t2);
    s.insert(t3);
    s.insert(t4);
      
    // define an iterator to iterate the whole set.
    set<struct Test>::iterator it; 
      
    for (it = s.begin(); it != s.end(); it++)
    {
        // print in ascending order as required.
        cout << (*it).id << endl; 
    }
      
    return 0;
}

Output:

101
102
110
115

Application:
a) Very useful while printing all distinct structure in sorted order.
b) Insert new structure in a sorted list of structures.

Want to learn from the best curated videos and practice problems, check out the C++ Foundation Course for Basic to Advanced C++ and C++ STL Course for foundation plus STL.  To complete your preparation from learning a language to DS Algo and many more,  please refer Complete Interview Preparation Course.



My Personal Notes arrow_drop_up
Recommended Articles
Page :