二元谓词对stl map和multimap的行为....

时间:2013-04-11 06:27:49

标签: c++ map comparator

我有以下代码:

#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放入二元谓词中时... 输出是: 1 1

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是将元素置于其前面还是后面。但我不知道这会如何影响地图本身的大小。 请详细说明一下。谢谢。

1 个答案:

答案 0 :(得分:2)

您的比较必须实现strict weak ordering。使用

时,不符合此要求
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
}