Nav*_*ngh 0 c++ equality key stdmap visual-c++
该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;
}
}
Run Code Online (Sandbox Code Playgroud)
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);
}
};
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
52 次 |
| 最近记录: |