Finding an element in a vector of structures

2019-06-03 20:09发布

问题:

I followed this https://stackoverflow.com/a/590005/1729501 answer and wrote below code.

#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;
}

This gives compilation errors

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&)’

If I move the find_element structure inside main(), I get below error,

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:

Could someone please tell me the correct syntax?

回答1:

You should provide the algorithm with function call operator (), not equality operator ==.

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

It is called functor in C++. See this answer for more detailed information.



回答2:

As others have already said, you need to implemented operator() not operator==.

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

Your usage is then correct:

std::find_if(vAlpha.begin(), vAlpha.end(),
    find_element(k))

If you're using C++11, you could alternatively use a lambda for this:

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

You can then completely omit your find_element struct - the one-line lambda does everything. Very concise!



回答3:

std::find_if needs an UnaryPredicate, try to overload operator():

struct find_element
{
    int y;

    find_element(int y) : y(y)
    {
    }

    bool operator()(const alpha& l)
    {
       return y == l.y;
    }
};


回答4:

your functor should overload the operator() not operator==

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

If you want to overload == then do it for the alpha struct and use std::find which will use operator== by default


Additional issues.
This is wrong

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

There is no element at 0 yet. you are assigning to a non-existent member. This is undefined behavior. It should be something like this

std::vector<alpha> vAlpha(1);
//                       ^^^  now it has 1 element
vAlpha[0].x = 10;
vAlpha[0].y = 100;

OR

std::vector<alpha> vAlpha;
alpha a;
a.x = 10;
a.y = 100; 
vAlpha.push_back(a);