Can I create a map with a dynamic constructed comparer?
I want to create std::map in STL, but the comparer depends some 开发者_运维知识库dynamic value which is available only at runtime.. How can I make this? For example, I want something looks like std::map<int, int, Comp(value1, value2)>
. value1 and value2 are not the compared number here, they are some kind of configuration numbers.
Use a functor class:
#include <map>
class Comp
{
public:
Comp(int x, int y) : x(x), y(y) {}
bool operator() (int a, int b) const { /* Comparison logic goes here */ }
private:
const int x, y;
};
int main()
{
std::map<int,float,Comp> m(Comp(value1,value2));
}
This is like a function, but in the form of a runtime object. This means it can have state, which includes runtime configuration. All you have to do is overload operator()
. If you define all the member-function bodies in the class definition (as above), then the compiler will probably inline everything, so there'll be negligible performance overhead.
If you know value1
and value2
at compile-time (i.e. if they are compile-time constants), you could use a function template instead:
template <int x, int y>
bool compare(int a, int b) { /* Comparison logic goes here */ }
int main()
{
std::map<int,float,compare<value1,value2> > m;
}
精彩评论