使用==运算符搜索矢量
Search a vector with == operator
我有一个类看起来像
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;
};
唯一需要注意的是,我定义了一个"=="运算符。
现在,给定一个向量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
接受三个参数。前两个是迭代器,指示要搜索的范围。如果要搜索整个向量,请分别传递向量的begin
和end
成员函数返回的迭代器。
Element tmp( 2,3 );
if( std::find( ele.begin(), ele.end(), tmp ) != ele.end() )
cout<< "found" ;
请注意,您应该声明比较运算符const。
bool operator==(Element const& rhs) const;
相关文章:
- C++矩阵类运算符使用 std::common_type_t 和复数的实现
- 对运算符=使用通用引用,而不是多个重载
- 如何在层次结构中实现运算符使用?
- 重载加法运算符(使用函数向对象添加字符串)
- 为什么sub_match和basic_string比较运算符使用额外的字符串副本实现?
- 通过运算符使用标量参数重写来修改类成员
- 重载运算符:使用C++文本时的操作数顺序
- 运算符[]使用朋友函数超载
- 重载前增量运算符使用重载后增量运算符内的变量结果
- 对链表复制构造函数和赋值运算符使用 copy() 方法
- 类型别名和运算符<<使用 ostream_iterator 重载会导致无效操作数
- qi%运算符使用(1)分隔符属性,(2)接受尾随分隔符
- 重载运算符<<使用指向字符串的指针
- 我应该为赋值运算符使用左值引用限定符吗
- 在C++11 std::atomic中,++、--和==等运算符使用的memory_order是什么
- C++ 重载运算符<<使用指针向量
- 运算符重载运算符 = 使用友元函数
- 通过 xor 运算符使用引用或指针交换两个变量的值
- 运算符<<使用temp变量工作,但不直接使用函数调用
- 对运算符+和/或运算符+=使用移动语义有意义吗