首页 > 解决方案 > 为什么 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并且它没有keyequalunordered_map. 此外,我无法控制它的定义,AsnObjectIdentifier因为它已经在其他头文件中定义。我怎样才能摆脱这种情况?

标签: c++visual-c++keyequalitystdmap

解决方案


您的比较不尊重严格的弱排序。

当您需要自定义为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);
    }
};

演示


推荐阅读