我正在使用多重映射来存储对原子 react 进行编码的对象。 multimap 看起来像这样:
std::multimap<ReactionElement, ReactionElement> reaction_map;
键是 react 物,值是产物。然后我遇到了这样一种情况,我找到了两个 react 物原子,我可以在图中查找这些 react 物可能形成的产物。
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 对,并将每个都插入到多重映射中。
问题是:当我去检索它们时,只有一些 react 是可访问的。对于某些 react ,我可以调用 reaction_map.find(reactant) 但什么也得不到。但是,我可以遍历多重映射,并看到我插入的所有对。我将其用作基本诊断:
for(multimap<ReactionElement, ReactionElement>::iterator it = reaction_map.begin();
it != reaction_map.end(); ++it)
std::cout << reaction_map.count(it->first) << '\n';
这打印了一些 ones、twos 和 zeros。这怎么可能?
有什么想法吗?
(编辑)下面详细介绍了比较运算符。我相当确定每个成员类都是有序的。我会确认。
// 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
要求此关系为 strict weak ordering .这意味着尤其是。以下规则:
-
!(x < x)
- 如果
(x < y)
, 然后!(y < x)
确保您的 operator<
实现符合这些规则。如果不是,请更改它或提供自定义 Comparator
对于 std::multimap
.
关于C++ multimap 查找失败,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34355836/