C++ 自定义映射键/值不按顺序排列
c++ customized map key/value not in order
我使用自定义结构构建了以下映射。
#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;
}
}
您的keyCompare
对std::map
无效。
它需要返回true
(a,b)
是否应在b
之前订购a
。
您编写了一个可以为(a,b)
和(b,a)
返回 true 的函数。 这违反了严格的弱排序。
相关文章:
- 为什么不;名字在地图上是按顺序排列的吗
- C++按字母顺序排列的字符串数组
- 如何在 c++ 中按字母顺序排列数组中的字符串?
- 尝试在 c++ 中按字母顺序排列单词时出现分段错误
- OpenGL,尽管按逆时针顺序排列,但一些法线还是反转了
- 有没有办法在不使用任何迭代的情况下将字符的字母顺序排列
- 我可以使用普通的气泡排序来按字母顺序排列列表吗?
- C 按顺序排列一个指针阵列
- 检查用户输入是否按字母顺序排列
- 数组内存地址总是按最小到最大的顺序排列吗
- 如何在C++上按字母顺序排列列表
- STL 优先级队列按递增顺序排列
- 正十进制整数的递归函数位数,按c++的相反顺序排列
- 按字母顺序排列单词
- 如何按大小写顺序排列字符串(而不是按字典顺序排列)
- C++ 自定义映射键/值不按顺序排列
- 按特定顺序排列矢量元素
- 检查文本文件是否按字母顺序排列
- 对的优先级队列以相反的顺序排列
- 如何将按字母顺序排列的BST排序为按频率排序的树