【发布时间】:2018-07-19 19:04:49
【问题描述】:
我无法让 std::map 查找以在 std::map 中找到正确的行。关键是一个类指针,我创建了一个结构 (tdEcApplDataMapEq) 来比较类的二进制数组是否匹配。'
问题是它不起作用。我在查找开始时调用 FoEcApplData::operator==。它说第一个条目不匹配,然后 find 返回指向 std::map 列表上的第一项。 find 没有尝试搜索其他映射条目。一个匹配测试也失败了(假),那么为什么 find 说它匹配呢?
这可能与 std::map 声明有关。 std::map 说第三个参数是 std::less,但我正在做一个 == vs.
如何让 find() 使用自定义结构进行搜索?
我的示例将 10 行添加到 FdTEcApplDataMap。它将 CDH_DISABLE_XACT182 类复制到保留以供稍后搜索。然后我使用 hold 作为搜索键进行 find() 测试。
Inside entry1
Inside entry2
Inside entry3<== this is the one I am searching for
Inside entry4
Inside entry5
Inside entry6
Inside entry7
Inside entry8
Inside entry9
Inside entry10
Inside entry1
这是发现:
auto hazard = ExcludedCmdDict.find(&hold);
if(hazard != ExcludedCmdDict.end())
{
std::cout << "found it " << hazard->second << std::endl;
}
这是正在使用的比较函数:
bool FoEcApplData::operator==( const FoEcApplData& FoEcApplDataObject) const {
if(myNumOfBytes <= FoEcApplDataObject.NumOfBytes())
{
const EcTOctet* temp;
temp = FoEcApplDataObject.Data() ;
for(EcTInt i = 0; i < myNumOfBytes ; i++)
{
if(myData[i] != temp[i])
{
return false ;
}
}
return true;
}
else // myNumOfBytes > FoEcApplDataObject.NumOfBytes()
{
const EcTOctet* temp;
temp = FoEcApplDataObject.Data() ;
for(EcTInt i = 0; i < FoEcApplDataObject.NumOfBytes(); i++)
{
if(myData[i] != temp[i])
{
return false ;
}
}
return true;
}
}
这是 std::map 的声明。
/*
Custom less for find on the FdTEcApplDataMap.
Needed since we are using pointers.
Returns - true - match, false - no match
node - pointer to the item you are looking for
node2 - pointer to an item on the list
*/
struct tdEcApplDataMapEq {
bool operator()(FoEcApplData *const& node, FoEcApplData *const& node2) const
{
return *node == *node2;
}
};
typedef std::map< FoEcApplData *, std::string, tdEcApplDataMapEq> FdTEcApplDataMap;
【问题讨论】: