Reputation: 992
I am trying to create a vector
of map
s. Each map
has a different comparator.
Here is what I have tried:-
#include<iostream>
#include<map>
#include<vector>
template <class T>
struct head {
virtual bool operator() (const T& x, const T& y) const = 0;
};
template <class T>
struct greater: head<T> {
bool operator() (const T& x, const T& y) const {return x>y;}
};
template <class T>
struct less: head<T> {
bool operator() (const T& x, const T& y) const {return x<y;}
};
int main()
{
std::vector<std::map<int, int, head<int>>> mp;
return 0;
}
But I am getting an error that my operator()
is pure virtual in head.
Please tell me what is the correct way to achieve this?
Upvotes: 1
Views: 176
Reputation: 249133
You need a single comparator type that works for all your vectors. Like this:
template<typename T>
struct comp {
comp(bool gt) : do_greater(gt) {}
bool operator() (const T& x, const T& y) const
{
return do_greater ? x > y : x < y;
}
bool do_greater;
};
int main()
{
std::vector<std::map<int, int, comp<int>>> mp;
mp.emplace_back(false); // first map uses less-than
mp.emplace_back(true); // first map uses greater-than
}
That is, the choice of comparison function needs to be driven by the state initialized in each std::map constructor. That single ?:
branch is probably better for performance than calling a virtual method every time, too.
Upvotes: 1