用C++11将compare函数传递给std::multiset



我有一个std::multiset,它存储std::对。我希望第一个属性对唯一性没有约束,但我希望第二个属性是唯一的。因此,我决定将我自己的函数传递给multiset,以实现这一点(如果没有,请告诉我)。

基于这个答案,我写了一个类似的函数,但它失败了,我不知道为什么(不知道λ-,我是希腊语:))。

auto f = [](std::pair<float, int>& a, std::pair<float, int>& b) {
  return (a.first < b.first && a.second != b.second);
};

错误:

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>’

由于您使用的是multiset,而不是set,因此比较相等的多个键仍将存储在容器中,因此我不确定您在谈论唯一性时的意思。

假设您的意思是只希望pair中的第二个元素影响排序,那么您可以使用如下lambda:

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);

实时演示

我认为不能将lambda(运行时构造)作为模板参数(编译时构造)传递。将结构与operator()一起使用反而有效:

#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;
}

或者,使用lambda和decltype(如Praetorian的回答):

#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;
}

最新更新