问题描述
我有一个std :: multiset,它存储std :: pair。我想第一个属性没有对唯一性的约束,但我想让第二个是唯一的。因此,我决定将自己的函数传递给multiset,以实现这一点(如果没有请让我知道)。
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: 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>’
推荐答案
我认为你不能传递lambda(运行时构造)作为模板参数(编译时构造)。使用 operator()
的结构代替:
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;
}
或者,使用lambda和decltype(如Praetorian的回答) p>
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;
}
这篇关于将我的比较函数传递给std :: multiset和C ++ 11的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!