c++ - 为什么 std::map.find() 在以下情况下不起作用?

标签 c++ visual-c++ key equality stdmap

snmp.h 头文件包含 AsnObjectIdentifier 结构的定义,不幸的是,该结构没有相等运算符重载。我希望 AsnObjectIdentifier 成为 std::map 的键,但问题是 find() 无法找到键 map 。我已经定义了一个自定义比较器 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 的情况下没有更多的模板参数,并且它没有像 unordered_map 中那样的 keyequal 参数。此外,我无法控制 AsnObjectIdentifier 的定义,因为它已在其他头文件中定义。我该如何解决这种情况?

最佳答案

您的比较不遵守严格的弱排序。

当您需要自定义为 std::tuple 时,我建议使用来自 STL 的帮助程序(使用 std::tie)或您的情况 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);
    }
};

Demo

关于c++ - 为什么 std::map.find() 在以下情况下不起作用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58879085/

相关文章:

c++ - LLVM 3.5中如何遍历支配树?

c++ - 通过作用域和类型枚举访问元组值失败

python - 在 Python 中使用对象作为字典中的键 - 哈希函数

ios - 如何从数组内的字典中的 'key' 获取 'value'?

visual-studio-2010 - 好的 MSbuild 日志格式化程序吗?

json - Jq:步行时测试 field

c++ - 在 Qt : Can I output to `stdout` , 中,我可以使用 qDebug() 输出到 `stderr` 吗?

c++ - 匹配 Eigen 和 Ceres-Solver 版本的最简单方法是什么?

c++ - vc++ 中预期的常量表达式

c# - 为什么 MouseMove 事件发生在 MouseUp 事件之后?