在结构向量中查找元素

use*_*107 1 c++ struct iterator vector

我按照这个/sf/answers/41300381/的答案写了下面的代码.

#include <iostream>
#include <algorithm>
#include <iterator>
#include <vector> 
using namespace std;

struct alpha {
    int x;
    int y;
};

struct find_element
{
    int y;
    find_element(int y) : y(y) {}
    bool operator ==( const alpha& l) const
    {
        return y == l.y;
    }
};

int main() {

    std::vector<alpha> vAlpha;
    vAlpha[0].x = 10;
    vAlpha[0].y = 100; 

    for(std::vector<alpha>::iterator it = vAlpha.begin(); it != vAlpha.end(); ++it) {
        int k = 100;
        // trying to find k in the complete vector
        if (vAlpha.end() == std::find_if( vAlpha.begin(), vAlpha.end(), find_element(k))) {
            cout << " not found! ";
        } else {
            cout << " found ";
        }
    }

    return 0;
}
Run Code Online (Sandbox Code Playgroud)

这会产生编译错误

In file included from /usr/include/c++/4.7/algorithm:63:0,
                 from prog.cpp:2: /usr/include/c++/4.7/bits/stl_algo.h: In instantiation of
‘_RandomAccessIterator std::__find_if(_RandomAccessIterator,
_RandomAccessIterator, _Predicate, std::random_access_iterator_tag) [with _RandomAccessIterator = __gnu_cxx::__normal_iterator<alpha*,
std::vector<alpha> >; _Predicate = find_element]’:
/usr/include/c++/4.7/bits/stl_algo.h:4490:41:   required from ‘_IIter
std::find_if(_IIter, _IIter, _Predicate) [with _IIter =
__gnu_cxx::__normal_iterator<alpha*, std::vector<alpha> >; _Predicate = find_element]’ prog.cpp:30:88:   required from here /usr/include/c++/4.7/bits/stl_algo.h:210:4: error: no match for call
to ‘(find_element) (alpha&)’
Run Code Online (Sandbox Code Playgroud)

如果我在find_element里面移动结构main(),我会得到以下错误,

prog.cpp: In function ‘int main()’: prog.cpp:31:88: error: no matching
function for call to ‘find_if(std::vector<alpha>::iterator,
std::vector<alpha>::iterator, main()::find_element)’ prog.cpp:31:88:
note: candidate is: In file included from
/usr/include/c++/4.7/algorithm:63:0,
                 from prog.cpp:2:
Run Code Online (Sandbox Code Playgroud)

有人可以告诉我正确的语法吗?

Tim*_*lds 5

正如其他人已经说过的那样,你需要实施的operator()不是operator==.

struct find_element
{
    int y;
    find_element(int y) : y(y) {}
    bool operator()(const alpha& l) const
    {
        return y == l.y;
    }
};
Run Code Online (Sandbox Code Playgroud)

您的用法是正确的:

std::find_if(vAlpha.begin(), vAlpha.end(),
    find_element(k))
Run Code Online (Sandbox Code Playgroud)

如果你正在使用C++ 11,你也可以使用lambda:

std::find_if(vAlpha.begin(), vAlpha.end(),
    [=](const alpha& l){ return k == l.y; })
Run Code Online (Sandbox Code Playgroud)

然后你可以完全省略你的find_element结构 - 单行lambda完成所有事情.非常简洁!