我需要找到两个具有相等字段的元素。它们应在同一向量中连续。我需要使用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
答案 0 :(得分:1)
使用neighbor_find代替find_if。您的代码应该可以使用。
std::vector<Sound>::iterator it = adjacent_find (iter, iterEnd, [](auto prev, auto next) -> bool {
return prev.getPitch() == next.getPitch();
答案 1 :(得分:1)
标准算法std::find_if
不接受二进制谓词。
您可以将标准算法std::adjacent_find
与lambda表达式一起使用。
成员函数getPitch
应该用限定符const
声明。在这种情况下,您可以将函数用于常量对象(例如,当Sound类型的对象或Sound对象的向量传递给接受常量引用的函数时)
这是一个演示程序
#include <iostream>
#include <vector>
#include <iterator>
#include <algorithm>
class Sound {
private:
int notePitch, length;
public:
Sound(int notePitch, int length) {
this->notePitch = notePitch;
this->length = length;
}
int getPitch() const {
// std::cout << "Pitch: " << this->notePitch << " length: " << this->length;
return this->notePitch;
}
};
int main( void )
{
std::vector<Sound> masterpiece = { { 1, 2 }, { 2, 3 }, { 2, 4 }, { 3, 5 } };
auto it = std::adjacent_find( std::begin( masterpiece ), std::end( masterpiece ),
[]( const Sound &a, const Sound &b )
{
return a.getPitch() == b.getPitch();
} );
if ( it != std::end( masterpiece ) )
{
std::cout << "Two adjacent elements are found at position "
<< std::distance( std::begin( masterpiece ), it )
<< '\n';
}
else
{
std::cout << "Two adjacent elements are found\n";
}
}
程序输出为
Two adjacent elements are found at position 1
您可以使用auto
[]( const auto &a, const auto &b )
{
return a.getPitch() == b.getPitch();
}
但是无论如何,最好将它们声明为const引用类型,因为在这种情况下,不会创建任何临时对象,并且lambda表达式保证不会更改其参数。