【发布时间】:2013-07-31 22:01:09
【问题描述】:
我有一个简单的类,我将它作为指针存储在向量中。我想在向量上使用 find 但找不到我的对象。在调试时,它似乎没有调用我提供的 == 运算符。我可以在调试器中“看到”对象,所以我知道它在那里。下面的代码甚至使用了列表中第一项的副本,但仍然失败。我可以让它通过的唯一方法是使用 MergeLine* mlt = LineList.begin(),这表明它正在比较对象而不是使用我的相等运算符。
class MergeLine {
public:
std::string linename;
int StartIndex;
double StartValue;
double FidStart;
int Length;
bool operator < (const MergeLine &ml) const {return FidStart < ml.FidStart;}
bool operator == (const MergeLine &ml) const {
return linename.compare( ml.linename) == 0;}
};
Class OtherClass{
public:
std::vector<MergeLine*>LineList;
std::vector<MergeLine*>::iterator LL_iter;
void DoSomething( std::string linename){
// this is the original version that returned LineList.end()
// MergeLine * mlt
// mlt->linename = linename;
// this version doesn't work either (I thought it would for sure!)
MergeLine *mlt =new MergeLine(*LineList.front());
LL_iter = std::find(LineList.begin(), LineList.end(), mlt);
if (LL_iter == LineList.end()) {
throw(Exception("line not found in LineList : " + mlt->linename));
}
MergeLine * ml = *LL_iter;
}
};
干杯, 马克
【问题讨论】:
-
当然不是。
a == b与*a == *b不同... -
指针是内置类型,所以它们不使用重载的
operator== -
您将向量指针存储在指向 MergeLine 而不是普通 MergeLine 对象中的任何特殊原因?再说了,不就是一个更适合你需求的智能指针吗?
-
@Antonio,坦率地说,我不记得我为什么将它实现为指针。回顾我的代码,我可以很容易地将它重新实现为对象。我可能会这样做。
-
注意:表达式
linename.compare( ml.linename) == 0可以更简单地写成linename == ml.linename