problem with find function in Vector of Structure in C++
I a开发者_C百科m trying to use the "find" function here. For that here's the code for the '==' operator. But I am getting a "too many parameters for this operator function" error at the word "operator".
Can anyone kindly help me out ? Thanks.
struct gr_log
{
string name;
string category;
string description;
float cost;
bool operator==(const gr_log& l, const gr_log& r) const
{
return l.name == r.name;
}
};
And:
vector<gr_log>::iterator it;
it = find (grocery.begin(), grocery.end(), "Sugar");
A member operator only takes one argument:
struct gr_log
{
string name;
string category;
string description;
float cost;
bool operator==(const gr_log& r)
{
return name == r.name;
}
};
Alternatively, you could write a friend
operator:
struct gr_log
{
string name;
string category;
string description;
float cost;
friend bool operator==(const gr_log& l, const gr_log& r)
{
return l.name == r.name;
}
};
Also, you'll need to perform a find
using an instance of gr_log because you can't compare a gr_log with a string like you're trying to do:
it = find (grocery.begin(), grocery.end(), gr_log("Sugar"));
Try this:
struct gr_log
{
string name;
string category;
string description;
float cost;
bool operator==(const string& name) {
return name == this->name;
}
};
This creates a ==
operator (using the correct syntax for member variable; it compares the explicit argument to the implicit this
), which compares a gr_log
to a string
. Since your std::find
call uses a string as a comparison object, you should be good to go.
As an alternative, you can define equality operators outside of your class:
struct gr_log
{
string name;
string category;
string description;
float cost;
};
inline bool operator==(const gr_log& gr, const string& name) {
return name == gr.name;
}
inline bool operator==(const sting& name, const gr_log& gr) {
return name == gr.name;
}
Note 1: The inline
keywords should be there if you are putting these in a header file, but not if you are putting them in a source file.
Note 2: Specifying both operator functions allows for the commutative property of equality.
Finally, in case this hasn't been hashed over enough -- the member equality operator takes one parameter, the non-member equality operator takes two.
operator == should not be a member of your structure. Or if it is, it should take 1 argument and compare it with this
:
struct gr_log
{ ...
bool operator==(const gr_log& l) const {return name == r.name;}
}
//or outside of the structure
bool operator==(const gr_log& l, const gr_log& r)
{
return l.name == r.name;
}
You have two choices: either a function bool operator==(a,b)
outside of the struct, or a bool operator==(other)
inside the struct.
精彩评论