c++ - 为什么 std::map.find() 在以下情况下不起作用?
问题描述
头snmp.h
文件包含AsnObjectIdentifier
结构的定义,不幸的是,这个结构没有相等运算符重载。我想AsnObjectIdentifier
成为 an 的关键,std::map
但问题是find()
无法在地图中找到关键。我已经定义了一个自定义比较器AsnObjectIdentifierComparator
,它作为 std::map 声明的第三个模板参数。该场景的最小可重现代码如下:
#include <iostream>
#include <string>
#include <map>
using namespace std;
typedef unsigned int UINT;
typedef struct {
UINT idLength;
UINT * ids;
} AsnObjectIdentifier;
struct AsnObjectIdentifierComparator {
bool operator()(const AsnObjectIdentifier& left, const AsnObjectIdentifier& right) const {
UINT* leftOidArr = left.ids, * rightOidArr = right.ids;
UINT smallerOidLen = (left.idLength < right.idLength ? left.idLength : right.idLength);
for (UINT i = 0; i < smallerOidLen; i++) {
if (leftOidArr[i] < rightOidArr[i]) {
return true;
}
}
if (smallerOidLen == left.idLength) {
return true;
}
return false;
}
};
typedef std::map<AsnObjectIdentifier, std::string, AsnObjectIdentifierComparator> MibMap;
int main(void){
MibMap map;
UINT expectedOID1ids[] = { 1, 3, 6, 1, 1, 1, 2, 1 };
AsnObjectIdentifier expectedOID1 = { 8, expectedOID1ids };
map.insert( std::pair<AsnObjectIdentifier, std::string>(expectedOID1, "present") );
cout << map.size() << endl;
if(map.find(expectedOID1) == map.end()) {
cout << "Not found" << endl;
}
}
定义键在映射中的放置顺序是有道理的,AsnObjectIdentifierComparator
但如果我们无法首先找到键,则没有用。在这种情况下没有更多的模板参数,std::map
并且它没有keyequal
像unordered_map
. 此外,我无法控制它的定义,AsnObjectIdentifier
因为它已经在其他头文件中定义。我怎样才能摆脱这种情况?
解决方案
您的比较不尊重严格的弱排序。
当您需要自定义为std::tuple
(with std::tie
) 或在您的情况下,我建议使用来自 stl 的助手std::lexicographical_compare
:
struct AsnObjectIdentifierComparator
{
bool operator()(const AsnObjectIdentifier& lhs, const AsnObjectIdentifier& rhs) const
{
return std::lexicographical_compare(lhs.ids, lhs.ids + lhs.idLength,
rhs.ids, rhs.ids + rhs.idLength);
}
};
推荐阅读
- tensorflow - 如何从 GAN 训练生成器?
- java - 使用 Maven 在多个 docker 容器中拆分测试
- python-3.x - 在 python 中有效地搜索巨大字典中的字符串/值
- bash - 如何在 shell 脚本中为布尔变量编写 if then?
- javascript - 如何通过nextjs中不同元素的onClick修改元素?
- javascript - 安排 node-cron 作业每天运行一次而不指定时间(每 24 小时一次)
- python - Pandas subsetting two dataframes based on rows that meet condition in one
- node.js - 从 webjob 调用 webapp 中的 API
- json - 自己的 toJSON 将对象对象放在本地存储中
- python - 在 MacOS Mojave 上从 PyInstaller 运行应用程序后如何修复 msgcat::mc 错误?