c++自定义映射键/值不按顺序

标签 c++ stl

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

#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<必须是不对称的才能成为 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;
    }
}

关于c++自定义映射键/值不按顺序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28132602/

相关文章:

c++ - 为什么我们不能自动推断返回类型?

c++ - 有没有办法将文字字符串放入 <char...> 模板中?

c++ - 声明 vector 时出现段错误

c++ - 我的 iOS Metal 计算内核是否存在编译器错误,或者我遗漏了什么?

c++ - 如何提供一个 std::vector 来匹配这个参数?

c++ - 事件处理程序是否可重入 Embarcadero C++Builder?

c++ - 如何查找指向 IPv6 地址的 SRV 记录

C++: std::vector::reserve 在包含指针时不保留

c++ - 简单链表与 STL::list。哪个最好?

c++ - 如何通过索引递增的generate_n填充STL容器