C++ set for user defined data type?


A set is a data structure that stores numeric values. The speciality of sets is that the elements are distinct (i.e. no two elements have the same value). Also the values are stored in ascending order. You can explicitly define the data type of a set in C++ i.e. a user defined data type for a set.

To store data in distinct form and in a sorted order. Let’s take an example,

Input  : 124689781230
Output : 1230467889

Logic

In a set the input can be in any order and there can be duplicate value. But the set will store only distinct values and in ascending order.

Example

 Live Demo

#include<bits/stdc++.h>
using namespace std;
struct Test {
   int id;
   bool operator < (const Test& t) const {
      return (this->id < t.id);
   }
};
int main() {
   Test t1 = { 12 }, t2 = { 45 }, t3 = { 32 }, t4 = { 78 }, t5 = {12}, t6 = {8};
   set<struct Test> s;
   s.insert(t1);
   s.insert(t2);
   s.insert(t3);
   s.insert(t4);
   s.insert(t5);
   s.insert(t6);
   set<struct Test>::iterator it;
   for (it = s.begin(); it != s.end(); it++) {
      cout << (*it).id <<" ";
   }
   return 0;
}

Output

8 12 32 45 78

Updated on: 04-Oct-2019

245 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements