std::find没有使用我定义的==运算符

std::find not using my defined == operator

本文关键字:定义 运算符 find std      更新时间:2023-10-16

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

欢呼,Marc

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

您可以使用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));

我认为您真正想要的是像这样使用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 ==(无论哪种形式)都可以更好地保存,以便进行真正的平等比较。

运算符重载不能使用指针,因为它不明确。

Bjarne Stroustrup:-

引入引用主要是为了支持运算符重载。C按值传递每个函数参数,其中传递对象根据值,用户可以传递指针。此策略在运算符过载的情况下不起作用习惯于在这种情况下,符号的便利性是必不可少的,因此用户如果对象是大的

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

   std::vector<MergeLine>LineList;
   std::vector<MergeLine>::iterator LL_iter;