tags:

views:

78

answers:

1

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.

+9  A: 

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;
}
Oli Charlesworth
The code is correct, but you don't really point out _why_ a functor is the solution. If you instantiate the map with the funtor _type_, you can (at runtime) pass a functor _object_ to the map constructor.
MSalters
@MSalters: Fair point. I've updated my answer slightly.
Oli Charlesworth