C++多映射查找失败
C++ multimap lookup failing
我使用多映射来存储编码原子反应的对象。多映射看起来像这样:
std::multimap<ReactionElement, ReactionElement> reaction_map;
关键是反应物,价值是产物。然后我遇到一种情况,我找到两个反应物原子,我可以在地图上查找这些反应物可能形成的产物
ReactionElements类的基本内容如下所示:
class ReactionElement {
friend bool operator==(const ReactionElement& lhs, const ReactionElement& rhs);
friend bool operator<(const ReactionElement& lhs, const ReactionElement& rhs);
public:
// Some methods here ...
private:
// The Atom class tracks the element
Atom atom_a;
Atom atom_b;
// SiteSpecies and NeighborSpecies classes track the reaction geometry
SiteSpecies site_species_a;
NeighborSpecies neighbor_species_b;
// int members track reaction energetics
int e_initial, e_transition, e_final;
double reac_distance;
}; // ReactionElement
我从一个文件中读取了一堆ReactionElement和ReactionElement对,并将每个对插入到多映射中。
问题是:当我去取回它们时,只有一些反应是可以访问的。对于某些反应,我可以调用reaction_map.find(reactor),但一无所获。但是,我可以在多映射中进行迭代,并且可以看到我插入的所有对。我用这个作为基本诊断:
for(multimap<ReactionElement, ReactionElement>::iterator it = reaction_map.begin();
it != reaction_map.end(); ++it)
std::cout << reaction_map.count(it->first) << 'n';
这打印了一些1、2和零。这怎么可能?
有什么想法吗?
(编辑)下面详细介绍了比较运算符。我相当确信每个成员类都是有序的。我会确认的。
// This directly compares each member (using a tolerance of .01 for reac_distance).
bool operator==(const ReactionElement& lhs, const ReactionElement& rhs) {
return (lhs.atom_a == rhs.atom_a and lhs.atom_b == rhs.atom_b and
lhs.site_species_a == rhs.site_species_a and
lhs.neighbor_species_b == rhs.neighbor_species_b and
lhs.e_initial == rhs.e_initial and lhs.e_transition == rhs.e_transition and
lhs.e_final == rhs.e_final and
fabs(lhs.hop_distance-rhs.hop_distance) <= 0.01);
}
// < orders on members in the order they appear in the class definition.
bool operator<(const ReactionElement& lhs, const ReactionElement& rhs) {
if (lhs.atom_a < rhs.atom_a)
return true;
else if (lhs.atom_a == rhs.atom_a and lhs.atom_b < rhs.atom_b)
return true;
else if (lhs.atom_a == rhs.atom_a and lhs.atom_b == rhs.atom_b and
lhs.site_species_a < rhs.site_species_a)
return true;
// etc for the remaining members.
return false;
}
迭代与count
/find
的区别在于count
和find
必须比较元素(迭代不需要)。默认情况下,std::multimap
使用std::less
进行比较。这相当于<
。std::multimap
要求这个关系是一个严格的弱序。这尤其意味着以下规则:
!(x < x)
- 如果为
(x < y)
,则为!(y < x)
确保您的operator<
实现符合这些规则。如果没有,请更改它,或为std::multimap
提供自定义Comparator
。
相关文章:
- 正在查找文档以获得PS4平台的C++中的设备信息
- 如果没有malloc,链表实现将失败
- 模板参数替换失败,并且未完成隐式转换
- 具有默认模板参数的多态类的模板推导失败
- 查找在 4 和问题中代码失败的测试用例
- 用于查找连续子数组的最大总和的代码使测试用例失败
- 驱动器号上的查找文件失败,但在路径上传递
- 如何查找 dll 注册失败的原因
- 动态链接到 c++ 静态成员字段时符号查找失败
- 查找下一个文件失败,出现空格字符
- 查找函数在失败结果中应该返回什么
- 查找第一个文件在根路径上失败
- JNA 程序函数查找失败
- 对于在类外定义的友元函数,模板上的隐式转换查找失败
- C++多映射查找失败
- 向后查找时,libvlc_media_player_set_position失败
- 当标准测试失败时,用于查找点是否在2D多边形内的替代测试
- 模板初始化列表-查找失败的原因
- 查找失败时增强string_algo返回值
- 删除[]失败,如何查找原因