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

问题描述 投票:0回答:2

snmp.h头文件包含AsnObjectIdentifier结构的定义,不幸的是,此结构没有相等运算符重载。我希望AsnObjectIdentifierstd::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的定义已在其他头文件中定义,因此我无法对其进行控制。如何解决这种情况?

c++ visual-c++ key equality stdmap
2个回答
1
投票

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


-2
投票

std :: map.find()正在使用Key in参数,您可以将expectedOID1传递给它。

© www.soinside.com 2019 - 2024. All rights reserved.