C++ 自定义映射键/值不按顺序排列

c++ customized map key/value not in order

本文关键字:顺序 排列 自定义 映射 C++      更新时间:2023-10-16

我使用自定义结构构建了以下映射。

#include <iostream>
#include <vector>
#include <map>
struct keys {
   int first;
   int second;
   int third;
};
struct keyCompare
{
   bool operator()(const keys& k1, const keys& k2) 
   {
    //return (k1.first<k2.first && k1.second<k2.second && k1.third<k2.third);
    return (k1.first<k2.first || k1.second<k2.second || k1.third<k2.third);
    //return (k1.first<k2.first || (k1.first==k2.first && k1.second<k2.second) || (k1.first==k2.first
    //  && k1.second==k2.second && k1.third<k2.third));
   }
};
int main()
{
   keys mk, mk1;
   int len = 4;
   //int myints1[9] = {1,2,3,4,5,6, 7,8,9};
   int myints1[12] = {1,2,3,4,5,6,1,2,3,1,2,3};
std::vector<int> input1(myints1, myints1+12);
std::map<keys, int, keyCompare> c2int;
for (int i = 0; i < len; i++) {
    mk.first = input1[i*3];
    mk.second = input1[i*3+1];
    mk.third = input1[i*3+2];
    c2int[mk] = i;
}
for (int i = 0; i < len;i++) {
    mk1.first = input1[i*3];
    mk1.second = input1[i*3+1];
    mk1.third = input1[i*3+2];
    std::cout << "map content " << c2int[mk1] << "n";
}
return 0;}

对于非重复键(如 {1,2,3,4,5,6,7,8,9}),代码按预期工作。回报是

map content is 0
map content is 1
map content is 2

但是当有重复的模式时,例如,键是{1,2,3,4,5,6,1,2,3}。打印输出是

map content is 2
map content is 1
map content is 2

当我期待时

map content is 0
map content is 1
map content is 0

由于键 {1,2,3} 已经分配了值 0。但是比较函数似乎将此键修改为值 2 而不是 0。我尝试了不同的比较功能,但它们都没有显示预期的输出。我想我在这种方法中错过了一些东西。有人可以解释一下吗?谢谢

此比较器不正确:

bool operator()(const keys& k1, const keys& k2) 
{
 return (k1.first<k2.first || k1.second<k2.second || k1.third<k2.third);
}

考虑{1,4,9}{2,3,4}{1,4,9} < {2,3,4}因为第一次比较,但后来{2,3,4} < {1,4,9}因为第二次比较!这显然不是你的本意!此外,operator<必须是不对称的才能成为严格弱排序,这是std::map所需要的。

您必须按顺序处理密钥:

bool operator()(const keys& k1, const keys& k2) {
    if (k1.first != k2.first) {
        return k1.first < k2.first;
    }
    else if (k1.second != k2.second) {
        return k1.second < k2.second;
    }
    else {
        return k1.third < k2.third;
    }
}

您的keyComparestd::map无效。

它需要返回true (a,b)是否应在b之前订购a

您编写了一个可以为(a,b)(b,a)返回 true 的函数。 这违反了严格的弱排序。