In this article we will see how to use std::set with user defined classes.

If you want to use std::set with user defined classes and use default sorting criteria then overload operator < in the class.

For example,

Suppose our class is Message that contains three properties i.e.
• Member content
• Sending User Name
• Receiving User Name

And to use this class objects in std::set with default sorting criteria we need to overload operator <.

Let’s see Message Class

According to above implementation of operator < function, two Message objects are compared on the bases of all the 3 properties.

So suppose we created 4 Message objects,

Here msg2 and msg4 are equal because

msg2 < msg4 is false AND msg4 < msg2 is false.

So, std::set will also treat msg4 as duplicate of msg2 as per current default sorting criteria i.e. operator <.

Now Let’s use this class in std::set,

user_3 :: user_1 :: Hello
user_1 :: user_2 :: Hello
user_1 :: user_3 :: Hello

But What if we enhance our requirement i.e.
Now we want to keep only single message sent by each user i.e. only one sent message is allowed per user. Then what ??

Option 1 :
Modify operator <, but then it can hamper our previous requirements and it might be possible that we don’t have write access to operator <.

Option 2:
Create a new set and use an external soring criteria i.e Comparator. We will discuss this in next article.


Python Recommendations:

C++ & C++11 Recommendations:

If you didn't find what you were looking, then do suggest us in the comments below. We will be more than happy to add that.

Subscribe with us to join 1500+ Python & C++ developers, to get more Tips &  Tutorials like this.