In this article we will see how to use external Sorting Criteria i.e. Comparator in std::set.

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

we want to keep only single message sent by each user i.e. only one sent message is allowed per user and we can’t modify operator <.


Use external sorting criteria i.e. comparator

Message Class,

Now create a Message comparator,

According to above implementation of comparator two Message objects are compared on the bases of all the sent user name.

So suppose we created 4 Message objects,

Here only msg1, msg2 and msg4 are equal because according to MessageUserComparator implementation.

So, if we insert all the above objects in std::set i.e.

Then out of 4 only 2 will be inserted.

Let’s use the message comparator with std::set of messages,

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

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.