snmp.h
头文件包含AsnObjectIdentifier
结构的定义,不幸的是,此结构没有相等运算符重载。我希望AsnObjectIdentifier
是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 :: map.find()正在使用Key in参数,您可以将expectedOID1
传递给它。