
- C++ Basics
- C++ Home
- C++ Overview
- C++ Environment Setup
- C++ Basic Syntax
- C++ Comments
- C++ Data Types
- C++ Variable Types
- C++ Variable Scope
- C++ Constants/Literals
- C++ Modifier Types
- C++ Storage Classes
- C++ Operators
- C++ Loop Types
- C++ Decision Making
- C++ Functions
- C++ Numbers
- C++ Arrays
- C++ Strings
- C++ Pointers
- C++ References
- C++ Date & Time
- C++ Basic Input/Output
- C++ Data Structures
- C++ Object Oriented
- C++ Classes & Objects
- C++ Inheritance
- C++ Overloading
- C++ Polymorphism
- C++ Abstraction
- C++ Encapsulation
- C++ Interfaces
C++ set for user define data type
Here we will see how we can make a set for user defined datatypes. The Set is present in C++ STL. This is a special type of data structure, it can store data in sorted order, and does not support duplicate entry. We can use set for any type of data, but here we will see how we can also use set for userdefined datatypes.
To use user-defined datatypes into stack, we have to override < operator, that can compare two values of that type. If this is not present, it cannot compare two objects, so the set cannot store data in sorted order, so will raise an exception.
Example
#include <iostream> #include<set> using namespace std; class Student { int id, marks; public: Student(int id, int marks){ this->id = id; this->marks = marks; } bool operator <(const Student& st) const{ //sort using id, return (this->id < st.id); } void display() const{ cout << "(" << id << ", " << marks << ")\n"; } }; main() { Student s1(5, 70), s2(3, 86), s3(2, 91), s4(2, 60), s5(1, 78), s6(6, 53), s7(4, 59); //the set will not consider duplicate id set<Student> st_set; st_set.insert(s1); st_set.insert(s2); st_set.insert(s3); st_set.insert(s4); st_set.insert(s5); st_set.insert(s6); st_set.insert(s7); set<Student>::iterator it; for(it = st_set.begin(); it != st_set.end(); it++){ it->display(); } }
Output
(1, 78) (2, 91) (3, 86) (4, 59) (5, 70) (6, 53)
- Related Articles
- C++ set for user defined data type?
- Program to define data structure that supports rate limiting checking for user in Python
- C++ map having key as a user defined data type
- Do I need to set up SAP user for every user of module?
- Program to find out the data type of user input in C++
- Program to define set data structure without using library set class in Python
- Must you define a data type when declaring a variable in JavaScript?
- How Can we permanently define user-defined variable for a client in MySQL?
- Set special characters for password while creating a new MySQL user?
- How MySQL reacts when we specify a CHARACTER SET binary attribute for a character string data type?
- What is the data type for unix_timestamp in MySQL?
- Best data type for storing large strings in MySQL?
- C++ Program for sorting variables of any data type
- Which MySQL data type is used for long decimal?
- How to set time data type to be only HH:MM in MySQL?

Advertisements