C++ – find struct in vector

cstructvector

I want to find a struct in a vector, but I'm having some troubles. I read several posts about this, but these all search for one element of the struct: I want to be able to compare multiple elements of the struct while searching. My struct and vector are defined as:

struct subscription {
    int tournamentid;
    int sessionid;
    int matchid;

    bool operator==(const subscription& m) const {
        return ((m.matchid == matchid)&&(m.sessionid==sessionid)&&(m.tournamentid==tournamentid));
    }
};

vector<subscription> subscriptions;

Then I want to search for a struct in the vector subscriptions, but since the combination of sessionid and matchid is unique, I need to search for both. Searching for only one will result in multiple results.

    subscription match;
    match.tournamentid = 54253876;
    match.sessionid = 56066789;
    match.matchid = 1108;
    subscriptions.push_back(match);

    it = find(subscriptions.begin(), subscriptions.end(), match);

The find function give the following error during compiling:

main.cpp:245:68: error: no match for ‘operator=’ in ‘it = std::find [with _IIter = __gnu_cxx::__normal_iterator >, _Tp = echo_client_handler::subscription](((echo_client_handler*)this)->echo_client_handler::subscriptions.std::vector<_Tp, _Alloc>::begin with _Tp = echo_client_handler::subscription, _Alloc = std::allocator, std::vector<_Tp, _Alloc>::iterator = __gnu_cxx::__normal_iterator >, typename std::_Vector_base<_Tp, _Alloc>::_Tp_alloc_type::pointer = echo_client_handler::subscription*, ((echo_client_handler*)this)->echo_client_handler::subscriptions.std::vector<_Tp, _Alloc>::end with _Tp = echo_client_handler::subscription, _Alloc = std::allocator, std::vector<_Tp, _Alloc>::iterator = __gnu_cxx::__normal_iterator >, typename std::_Vector_base<_Tp, _Alloc>::_Tp_alloc_type::pointer = echo_client_handler::subscription*, (*(const echo_client_handler::subscription*)(& match)))’

And a WHOLE lot more 🙂 So the operator is not defined correctly, but how should that be done? Can anyone help me? How to search for multiple elements instead of only one element of a struct?

Best Answer

May be you did not specified type for it?

std::vector<subscription>::iterator it = 
    find(subscriptions.begin(), subscriptions.end(), match);
Related Topic