问题
I have a std::multiset, which stores std::pair. I want the first attribute to have no constraint on uniqueness, but I want the second one to be unique. So, I decided to pass my own function to multiset, in order to achieve this (if not please let me know).
Based on this answer, I wrote a similar function but it fails, and I have no idea why (no idea of λ - and I am Greek :) ).
auto f = [](std::pair<float, int>& a, std::pair<float, int>& b) {
return (a.first < b.first && a.second != b.second);
};
Error:
error: expression ‘#‘lambda_expr’ not supported by dump_expr#<expression error>’ is not a constant-expression
sorry, unimplemented: non-static data member initializers
error: unable to deduce ‘auto’ from ‘<expression error>’
回答1:
I think you cannot pass a lambda (runtime construct) as a template parameter (compile-time construct). Using a struct with operator()
works instead:
#include <set>
struct my_compare {
bool operator() (const std::pair<float, int>& a, const std::pair<float, int>& b) {
return (a.first < b.first && a.second != b.second);
};
};
int main(int argc, char ** argv) {
std::multiset<std::pair<float, int>, my_compare> set;
return 0;
}
Or, with a lambda and decltype (as in Praetorian's answer):
#include <set>
int main(int argc, char ** argv) {
auto my_compare = [](const std::pair<float, int>& a, const std::pair<float, int>& b) {
return (a.first < b.first && a.second != b.second);
};
std::multiset<std::pair<float, int>, decltype(my_compare)> set(my_compare);
return 0;
}
回答2:
Since you're using a multiset
, and not a set
, multiple keys that compare equal will still be stored in the container, so I'm not sure what you mean when you talk about uniqueness.
Assuming you meant you only want the second element in the pair
to affect ordering, you can use a lambda as follows:
auto f = [](std::pair<float, int> const& a, std::pair<float, int> const& b) {
return a.second < b.second;
};
std::multiset<std::pair<float, int>, decltype(f)> m(f);
Live demo
来源:https://stackoverflow.com/questions/25777396/passing-my-compar-function-to-stdmultiset-with-c11