gpt4 book ai didi

c++ - 使用 == 运算符搜索 vector

转载 作者:行者123 更新时间:2023-11-28 06:35:38 25 4
gpt4 key购买 nike

我有一个类看起来像

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;

};

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

现在,给定一个 vector Elements ( vector<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需要三个参数。前两个是指示搜索范围的迭代器。如果要搜索整个 vector ,请分别传递 vector 的 beginend 成员函数返回的迭代器。

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

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

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

关于c++ - 使用 == 运算符搜索 vector ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26826264/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com