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

标签 c++ vector

我有一个类看起来像

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/

相关文章:

c++ - 为什么 C++ 模板接受数组并不比一个接受指针 (bis) 更专业?

c++ - 在 C++ 数组快速 SIMD 版本中寻找短值

r - 查找包含一小部分 0 的最大长度子向量

python - 使用 R 或 python 在坐标系中绘制向量

c++ - 这是一个好主意吗 : Class that sums pointers from a vector, 这样相等比较很快

c++ - C++隐式复制构造函数成员变量复制顺序

c++ - 在 C++ 中将单反斜杠转换为双反斜杠

c++ - 强制 GCC 将 .cpp 文件编译为 C

c++ - 接受 vector 、索引和返回元素的函数

c++ - C++ vector 中没有可行的重载 '='