c ++自定义地图键/值不按顺序排列

时间:2015-01-25 02:28:52

标签: c++ stl

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

#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.我尝试了不同的比较函数,但它们都没有显示预期的输出。我想我错过了这种方法。谁能解释一下?感谢

2 个答案:

答案 0 :(得分:1)

此比较器不正确:

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

考虑{1,4,9} vs {2,3,4}{1,4,9} < {2,3,4}因为第一次比较,但后来{2,3,4} < {1,4,9}因为第二次!那显然不是你想要的!此外,operator<必须是非对称的才能成为StrictWeakOrdering,这是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;
    }
}

答案 1 :(得分:0)

您的keyComparestd::map无效。

如果在true之前订购(a,b),则需要返回a b

您编写的函数可以为(a,b) (b,a)返回true。这违反了strict weak ordering