我需要找到两个具有相等字段的元素。它们在同一个 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/