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?
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 ofbool
. 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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With