STL映射和multimap中二元谓词的行为…
behaviour of binary predicate for stl map and multimap....
我有以下代码:
#include <iostream>
#include <stdio.h>
#include <cmath>
#include <map>
using namespace std;
struct vals
{
int cods[5];
int sz;
};
struct myComp
{
bool operator()(vals A, vals B) const
{
int i=0;
while(A.cods[i]==B.cods[i] && i<A.sz)
i++;
if(i==A.sz)
return false; //<-----this is the value im changing..
else
return A.cods[i] > B.cods[i];
}
};
map< vals, int, myComp> Mp;
int main()
{
vals g, h;
g.sz=h.sz=3;
g.cods[0] = 12;
g.cods[1] = 22;
g.cods[2] = 32;
Mp.insert(pair< vals, int >(g,4));
Mp.insert(pair< vals, int >(g,7));
cout<<Mp.count(g)<<endl;
cout<<Mp.size()<<endl;
return 0;
}
现在,当将Mp
声明为map,并将false
放在二进制谓词中。输出为:11
Mp => map && binary predicate:true ==> output: 0 2
Mp => multimap && binary predicate:true ===> output: 0 2
Mp => multimap && binary predicate:false ===> output: 2 2
我认为谓词的返回值只是告诉stl
是否将元素放在它的前面或后面。但我不明白这对地图本身的大小有什么影响……请解释一下。谢谢你。
您的比较必须实现严格的弱排序。当使用
时,不满足此要求if(i==A.sz)
return true;
比较器中的。在本例中,数组中的所有元素都相同。如果两个实参相等,函子不能返回true
。如果没有严格的弱排序比较,映射就不能正常工作。
可以使用std::lexicographical_compare
:
#include <algorithm> // for std::lexicographical_compare
#include <functional> // for std::greater
...
bool operator()(vals A, vals B) const
{
return std::lexicographical_compare(A, A+A.sz, B, B+B.sz); // less-than
//return std::lexicographical_compare(A, A+A.sz, B, B+B.sz, std::greater<int>()); // gt
}
相关文章:
- std::condition_variable::wait()如何评估给定的谓词
- 有没有办法将谓词中的元素偏移量传递给 std 算法?
- 如何在 STL 函数中找到传递给谓词的元素的索引?
- 为 C++11 算法组合多个谓词
- 处理 std::enable_if<...中谓词的逻辑"OR">
- std::map与谓词与初始化列表
- 尝试使用谓词函数会导致错误:"std::sort"未找到匹配的重载函数
- 如何有效地操作满足给定谓词的向量中的所有项目?
- 排序谓词没有传递对索引对象的引用?
- 将 unordered_map 与 Catch2 谓词一起使用时类型不匹配
- C++函数,它将数组、谓词和运算符作为参数,并将运算符应用于满足谓词的数组元素
- 重写派生类中的二元运算符
- 如何在算法中使用谓词函数find_if?
- 是否可以使用三元切换/控制/谓词成员函数调用?
- 评估C 中的二元谓词
- 在使用二元谓词的find_first_of函数上给出错误
- Std:list.sort(),二元谓词
- 实现推力二元谓词
- STL映射和multimap中二元谓词的行为…
- 理解Thrust中的二元谓词