Delta_Fore
Delta_Fore

Reputation: 3271

Using lambda function as a compare for a std::map

In VS2015 why can I do this

typedef std::pair<std::set<std::string>::const_iterator,std::set<std::string>::const_iterator> paircmpiter;
struct PairCmp {
    bool operator()(const paircmpiter& lhs, const paircmpiter& rhs) const {
        return (*lhs.first + *lhs.second) < (*rhs.first + *rhs.second);
    }
};
std::map <paircmpiter,std::vector<std::pair<std::set<std::string>::const_iterator, int>>, PairCmp> markov;

but not this

auto paircmp = [](const paircmpiter& lhs, const paircmpiter& rhs) {
    return (*lhs.first + *lhs.second) < (*rhs.first + *rhs.second);
};
std::map <paircmpiter,std::vector<std::pair<std::set<std::string>::const_iterator, int>>, decltype(paircmp)> markov;

I would have expected the decltype would allow me to use lambda functions as a comparison.

How do I make it work using the lambda syntax?

Upvotes: 1

Views: 1252

Answers (1)

Maxim Egorushkin
Maxim Egorushkin

Reputation: 136266

You get a compilation error because closure objects created by lambda expressions are not default-constructible. But they are copy-constructible.

To fix, you need to pass the closure object into std::map constructor that takes a Compare object:

std::map<
    paircmpiter,
    std::vector<std::pair<std::set<std::string>::const_iterator, int> >,
    decltype(paircmp)
    > markov{paircmp}; // <--- here

Upvotes: 1

Related Questions