STL映射和multimap中二元谓词的行为…

behaviour of binary predicate for stl map and multimap....

本文关键字:谓词 二元 映射 multimap STL      更新时间:2023-10-16

我有以下代码:

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