c++ - 如何比较c++列表中的两个连续元素

标签 c++ algorithm stl find

我需要找到两个具有相等字段的元素。它们在同一个 vector 中应该是连续的。我需要用STL方法来做。我试过使用 find 或 find_if 但做不到。你能给我任何提示吗?

我的代码(部分):

class Sound {
    private:
        int notePitch, length;
    public:
        Sound(int notePitch, int length) {
            this->notePitch = notePitch;
            this->length = length;
        }
        int getPitch() {
            std::cout << "Pitch: " << this->notePitch << " length: " << this->length;
            return this->notePitch;
        }
    };

实际的查找函数:

std::vector<Sound>::iterator iter = masterpiece.begin();
std::vector<Sound>::iterator iterEnd = masterpiece.end();   
std::vector<Sound>::iterator it = find_if(iter, iterEnd, [](auto prev, auto next) -> bool {                 
    return prev.getPitch()  == next.getPitch(); 
});

我得到的错误是这样的:

c2678 binary '==' no operator found which takes a left-hand operand of type

最佳答案

使用 adjacent_find 代替 find_if。您的代码应该可以工作。

std::vector<Sound>::iterator it = adjacent_find (iter, iterEnd, [](auto prev, auto next) -> bool {                 
    return prev.getPitch()  == next.getPitch(); 

关于c++ - 如何比较c++列表中的两个连续元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56857634/

相关文章:

c++ - 防止反向工程 C++ 二进制文件

c++ - Dijkstra 算法 - 无限循环

algorithm - 最好的最短路径算法

c++ - std::fstream 和 Boost Iostreams 库之间的区别

c++ - STL 流 : forward operator<< calls 的包装类

c++ - 使用 boost::bind 排序

c++ - CWinThread 被 AfxBeginThread 创建后谁拥有它?

algorithm - 从轴对齐照片进行 3D 重建

algorithm - 是否有更适合 CISC 或 RISC 的算法或某些编程风格?

c++ - 为什么这个重载函数的调用不明确?