【发布时间】:2012-06-21 09:39:34
【问题描述】:
我使用的是一个非常简单的结构,映射,定义如下:
struct mapping{
int code;
string label;
bool operator<(const mapping& map) const {
return code < map.code;
}
bool operator==(const mapping& map) const {
return label.compare(map.label) == 0 ;
}
};
我想创建一组按他们的代码排序的映射。为此,我重载了
当我尝试插入具有相同代码但不同标签的映射时,问题就出现了。实际上,在该过程的第二步中,我不知道之前是否插入了具有相同标签的映射。所以,我需要调用 find() 函数来确定是否是这种情况。如果没有插入相同标签的映射,没关系,我只需要插入这个新的(但它的代码将暂时与其他映射相同)。如果存在一个具有相同标签的映射,我只需要更新它的代码。我虽然像我一样重载 == 运算符就足够了,但事实并非如此,如下面的代码所示。
mapping m = {1,"xxx"};
mapping m2 ={1, "yyy"};
this->fn[0].insert(m);
set<mapping>::iterator itTmp;
itTmp = this->fn[0].find(m2);
if (itTmp != this->fn[0].end() ) {
cout << "m2 exists "<<endl;
if ( !(*itTmp == m2) ){
cout << "But it is different according to the definition of the == operator "<<endl;
}
}
相关的输出是:
m2 exists
But it is different according to the definition of the == operator
我该如何解决这个问题并设法处理具有非常不同语义的运算符
谢谢,
约安
【问题讨论】:
-
顺便说一句,operatorstd::set<mapping, SpecialOrdering> specialOrderedSet
-
@stefaanv 所以
std::string("that")小于std::string("this")?包含 1 和 10 的std::set<int>小于仅包含 2 的std::set<int>? -
@aschepler:是的,显然,即使对于一个没有多大意义的集合。您似乎不同意我写的内容,但我不确定您的意思。我的观点是,如果您使用 operator