用C++11将compare函数传递给std::multiset
Passing my compar function to std::multiset with C++11
我有一个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;
}
相关文章:
- 使用std::multimap迭代器创建std::list
- C++中std::resize(n)和std::shrink_to_fit之间的区别
- C++:将 std::set_union() 输出存储在 std::multiset 中
- 如何为包含最多N个元素的std::multiset调用最大数量分配
- 为什么 [std::unique] 不能应用于 [std::multiset]?
- 试图理解libstdc++对std::multiset的实现
- std::multiset::iterator = NULL 不再有效
- std::multiset<A>的模板参数 A、B 分别是什么意思,它是如何工作的?
- 在STD :: MultiSet中维护插入顺序
- 哪个元素将从 std::multimap::find 返回,同样,std::multiset::find
- std::multiset并查找中间元素
- std::multiset vs. std::<int>map<int, std::size_t> 用于保留多个可重复的整数值
- 在std::multiset中,如果找到一个元素,有一个函数或算法可以只擦除一个样本(单播或重复)
- 从std::multiset的第i个元素删除到末尾
- 用C++11将compare函数传递给std::multiset
- 输出“std::multiset”的唯一元素及其频率,使用C++中的std::算法(无循环)
- 对std::multiset内的相等范围进行排序
- 在“std::multiset”的唯一元素上迭代
- 如何使用std::multiset与多个比较器函数
- C++ std::set and std::multiset