Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Finding a struct in a vector

Tags:

c++

vector

I want to find a struct whose all member data match certain values.

I made a following short program:

#include <iostream>
#include <vector>
using namespace std;
struct vlan {
    int vlanId;
    bool status;
};

vector<vlan> vlanTable; 

int main(){
    vlan tmp;
    tmp.status = true;
    tmp.vlanId = 1;
    vector <vlan>::iterator flag = find(vlanTable.begin(), vlanTable.end(), tmp);
    if ( flag != vlanTable.end()){
        cout<<"found"<<endl;
    }
    else cout<<"not found"<<endl;
    return 0;
}

It returns error as: template argument deduction/substitution failed right at the find function.

Could someone help me?

like image 933
Minh Pham Avatar asked Dec 08 '22 09:12

Minh Pham


1 Answers

You need to provide the == operator for your vlan class:

struct vlan {
    int vlanId;
    bool status;
    bool operator==(const vlan& rhs) const {
        return (vlanId == rhs.vlanId) && (status == rhs.status);
    }
};

Also, as noted in the comments, you should #include <algorithm> (for the definition of std::find); some compilers may implicitly include this from other headers, but don't rely on that.


Note that, as per the comment made by aschepler, if you have a compiler that conforms to the C++20 (or later) Standard, you can define the operator== for your vlan class as defaulted:

struct vlan {
    int vlanId;
    bool status;
    bool operator==(const vlan& rhs) const = default; // C++20
};

For your vlan struct, this will perform the exact same comparison(s) as the 'explicit' version defined above. From cppreference (or the Draft C++20 Standard itself):

Defaulted equality comparison

A class can define operator== as defaulted, with a return value of bool. This will generate an equality comparison of each base class and member subobject, in their declaration order. Two objects are equal if the values of their base classes and members are equal. The test will short-circuit if an inequality is found in members or base classes earlier in declaration order.

like image 63
Adrian Mole Avatar answered Dec 27 '22 06:12

Adrian Mole