std::set
is a C++ STL container that store unique elements following a specific order. It is defined in the set
header file.
Benefits and Features of std::set
[3]:
- It’s doesn’t allow duplicate elements i.e. it only contains unique elements
-
std::set
can contain element of any specified type in template argument -
std::set
internally store elements in balanced binary tree -
By default
std::set
uses the operator<
for comparing two elements and but if user passes the external sorting criteria i.e. comparator then it uses it instead of default operator<
. -
std::set
will keep the inserted elements in sorted order based on the assigned sorting criteria i.e. either by default criteria operator<
or by passed comparator (if passed).
In this post the samples only limited to std::set
that use custom comparator and store complex object instead of basic data type. The complex object that we will use is reusing class Person
on previous post.
Let’s create custom class that handles comparation process
#ifndef CustomCompare_h
#define CustomCompare_h
#include "Person.hpp"
struct CustomCompare
{
bool operator()(const int& lhs, const int& rhs)
{
return lhs < rhs;
}
bool operator()(const Person& lhs, const Person& rhs)
{
return lhs.getAge() < rhs.getAge();
}
};
#endif /* CustomCompare_h */
The following code is an example how to use the comparator class in std:set
void SampleSetWithCustomCompare()
{
set<Person,CustomCompare> setOfPersons;
setOfPersons.insert(Person("Person 1", 25));
setOfPersons.insert(Person("Person 2", 16));
setOfPersons.insert(Person("Person 3", 28));
setOfPersons.insert(Person("Person 4", 9));
for(set<Person,CustomCompare>::iterator it = setOfPersons.begin(); it!=setOfPersons.end(); ++it)
{
cout << it->getName() << " , age : " << it->getAge()<< endl;
}
}
References
- http://www.cplusplus.com/reference/set/set/
- http://www.wrox.com/WileyCDA/WroxTitle/Professional-C-2nd-Edition.productCd-0470932449.html
- http://thispointer.com/stdset-tutorial-part-1-set-usage-details-with-default-sorting-criteria/