2

我有一个简单的类,我将它作为指针存储在向量中。我想在向量上使用 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;

    }
};

干杯,马克

4

3 回答 3

2

由于您的容器包含指针而不是对象,因此比较将在指针之间进行。指针相等的唯一方法是它们指向完全相同的对象。正如您所注意到的,对象本身的比较运算符永远不会被调用。

您可以使用std::find_if并将其传递给要使用的比较对象。

class MergeLineCompare
{
    MergeLine * m_p;
public:
    MergeLineCompare(MergeLine * p) : m_p(p)
    {
    }
    bool operator()(MergeLine * p)
    {
        return *p == *m_p;
    }
};

LL_iter = std::find_if(LineList.begin(), LineList.end(), MergeLineCompare(mlt));
于 2013-07-31T22:24:19.557 回答
1

我认为你真正想要的是这样使用std::find_if

struct MergeLineNameCompare
{
    std::string seachname;

    MergeLineNameComp(const std::string &name) : seachname(name)
    {
    }

    bool operator()(const MergeLine * line)
    {
        return seachname.compare( line->linename ) == 0;
    }
};

LL_iter = std::find_if(LineList.begin(), LineList.end(), MergeLineNameCompare(linename) );

operator ==无论哪种形式)都可以更好地保存以进行真正的相等比较。

于 2013-07-31T22:25:19.693 回答
0

运算符重载不能与指针一起使用,因为它是模棱两可的。

Bjarne Stroustrup :-

引入引用主要是为了支持运算符重载。C 按值传递每个函数参数,如果按值传递对象效率低下或不合适,用户可以传递指针。此策略在使用运算符重载的情况下不起作用。在这种情况下,符号方便是必不可少的,因此如果对象很大,则不能期望用户插入运算符的地址。

所以,可能不是最好的,但仍然:-

   std::vector<MergeLine>LineList;
   std::vector<MergeLine>::iterator LL_iter;
于 2013-07-31T22:49:31.590 回答