C++ Custom Comparators for container

Poby’s Home
2 min readAug 26, 2021

useful to sort automatically as you insert elements

Custome comparator

#include <set>
#include <string>
struct MyData
{
MyData(const std::string& str, int v) : key(str), value(v) {}
std::string key;
int value;
};
struct Compare
{
bool operator()(const MyData &lhs, const MyData &rhs) const
{
return lhs.key < rhs.key;
}
};
int main()
{
std::set<MyData, Compare> myset;
myset.insert(MyData("Bob", 1));
}

Built-in comparator

For container types such as priority_queue, you can use built-in compare such as std::greater<int>, std::less<int>

with priority_queue, greater<> makes asending order, less<> makes descending order.

std::priority_queue(int, vector<int>, std::greater<int>> q; // asc
std::priority_queue(int, vector<int>, std::less<int>> q; // dsc

greater / less can be used for sort.

// greater example
#include <iostream> // std::cout
#include <functional> // std::greater
#include <algorithm> // std::sort

int main () {
int numbers[]={20,40,50,10,30};
std::sort (numbers, numbers+5, std::greater<int>());
for (int i=0; i<5; i++)
std::cout << numbers[i] << ' ';
std::cout << '\n';
return 0;
}
Output:50 40 30 20 10

Compare function

For Non-Container such as std::sort, a simple boolean function

static bool comparator(const vector<int>& a, const vector<int>& b) {
return a[0] < b[0]; // acending order
}
std::sort(input.begin(), input.end(), comparator);

Class vs Object?

sort() → takes compare object

template< class RandomIt, class Compare >
constexpr void sort( RandomIt first, RandomIt last, Compare comp );
ex)
int numbers[] = {20, 40, 50, 10, 30};
std::sort(numbers, numbers + 5, std::greater<int>());

set<> → takes class

template<class Key,
class Compare = std::less<Key>,
class Allocator = std::allocator<Key>
> class set;
ex)
set<shared_ptr<MyData>, Compare> myData;

priority queue <>→ takes class

template<class T,
class Container = std::vector<T>,
class Compare = std::less<typename Container::value_type>
> class priority_queue;
ex)
std::priority_queue<int, std::vector<int>, std::greater<int>> pq(data.begin(), data.end());

--

--