使用==运算符搜索矢量

Search a vector with == operator

本文关键字:运算符 使用 搜索      更新时间:2023-10-16

我有一个类看起来像

class Element
{
public :
    Element(int im_index, int seg_index)
    {
        imIndx = im_index;
        segIndx = seg_index;
    }
    Element() { imIndx=-1 ; segIndx=-1; }
    void getData( int & toReturnImIndx, int & toReturnSegIndx )
    {
        toReturnImIndx = imIndx;
        toReturnSegIndx = segIndx;
    }
    // Specific for disjoint_sets
    size_t dsID;
    size_t dsRank;
    size_t dsParent;
    bool operator==(Element const& rhs);
    bool operator!=(Element const& rhs);
    bool compareByParent(Element const& rhs);
private:
    int imIndx;
    int segIndx;
};

唯一需要注意的是,我定义了一个"=="运算符。

现在,给定一个向量Elementsvector<Element>)如何搜索其中的元素,我知道它有一个函数std::find。此函数询问比较函数。如何指定"=="运算符。

我想像一样使用它

vector<Element> ele;
// populate the ele
Element tmp( 2,3 );
if( find( ele, tmp ) )
    cout<< "found" ;
else
    cout<< "not found";

std::find接受三个参数。前两个是迭代器,指示要搜索的范围。如果要搜索整个向量,请分别传递向量的beginend成员函数返回的迭代器。

Element tmp( 2,3 );
if( std::find( ele.begin(), ele.end(), tmp ) != ele.end() )
    cout<< "found" ;

请注意,您应该声明比较运算符const。

bool operator==(Element const& rhs) const;