使用C++ 11将我的compar函数传递给std :: multiset

gsa*_*ras 2 c++ lambda stl multiset c++11

我有一个std :: multiset,它存储std :: pair.我希望第一个属性对唯一性没有约束,但我希望第二个属性是唯一的.所以,我决定将自己的功能传递给multiset,以实现这一目标(如果不是请告诉我).

根据这个答案,我写了一个类似的功能,但它失败了,我不知道为什么(不知道λ - 我是希腊:)).

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

错误:

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>’
Run Code Online (Sandbox Code Playgroud)

Pra*_*ian 6

由于你使用的是一个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);
Run Code Online (Sandbox Code Playgroud)

现场演示

  • @ G.Samaras你接受最好的答案,这里没有公平竞争的问题.我们不玩游戏.那些使用SO获得声誉而不是知识的人是傻瓜. (2认同)