C++ stl映射和多重映射的二进制谓词行为。。。。

C++ stl映射和多重映射的二进制谓词行为。。。。,c++,map,comparator,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[

我有以下代码:

#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;
}
#包括
#包括
#包括
#包括
使用名称空间std;
结构VAL
{
int-cods[5];
int sz;
};  
结构mycop
{
布尔运算符()(VAL A,VAL B)常数
{
int i=0;
而(A.cods[i]==B.cods[i]&&imp;
int main()
{
缬氨酸g,h;
g、 sz=h.sz=3;
g、 cods[0]=12;
g、 cods[1]=22;
g、 cods[2]=32;
Mp.插入(成对(g,4));
Mp.插入(成对(g,7));

cout您的比较必须实现一个。当您使用

if(i==A.sz)
    return true;
在比较器中。在这种情况下,数组中的所有元素都相同。如果函子的两个参数相等,则函子无法返回
true
。如果没有严格的弱顺序比较,则映射无法正确运行

通过使用以下命令,可以大大简化函子:

#include//for std::lexicographical\u比较
#包含//用于std::更大
...
布尔运算符()(VAL A,VAL B)常数
{
return std::lexicographical_compare(A,A+A.sz,B,B+B.sz);//小于
//返回std::lexicographical_compare(A,A+A.sz,B,B+B.sz,std::greater());//gt
}

+1实现你的函子:如果(a#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 }