在C++中的结构向量中查找函数的问题

问题描述:

我试图在这里使用“查找”功能。为此,这里是'=='运算符的代码。但是,我在“操作员”一词中得到了“这个操作员功能的参数太多”的错误。在C++中的结构向量中查找函数的问题

任何人都可以帮助我吗?谢谢。

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

}; 

和:

vector<gr_log>::iterator it; 
it = find (grocery.begin(), grocery.end(), "Sugar"); 

成员运营商只需要一个参数:

struct gr_log 
{ 
    string name; 
    string category; 
    string description; 
    float cost; 
    bool operator==(const gr_log& r) 
    { 
     return name == r.name; 
    } 
}; 

或者,你可以写一个friend操作:

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

此外,您需要使用gr_log的实例执行find,因为您无法将gr_log与字符串比较,如you'r Ë试图做:

it = find (grocery.begin(), grocery.end(), gr_log("Sugar")); 
+0

在一个结构中,没有理由使它成为“朋友”。只需将操作员定义为班级以外的非成员。 – 2011-06-14 23:18:04

+0

“朋友”的原因是什么? – a1ex07 2011-06-14 23:19:25

+0

@ a1ex07:'friend'可以访问'gr_log'的'private'成员(或任何出现“friend”的类)。由于它是一个POD结构,所有成员都是公共的,而'朋友'只会增加混淆。 – 2011-06-14 23:21:04

==操作符不应该是你的结构中的一员。或者,如果是,则需要花费1个参数,并比较其与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; 
} 
+0

那么,我该怎么办? – Ahsan 2011-06-14 23:16:10

+0

@Ahsan:看看更新后的版本。 – a1ex07 2011-06-14 23:18:59

你有两个选择:要么是功能bool operator==(a,b)外结构的,或bool operator==(other)的结构里面。

尝试这种情况:

struct gr_log 
{ 
    string name; 
    string category; 
    string description; 
    float cost; 
    bool operator==(const string& name) { 
    return name == this->name; 
    } 
}; 

这产生了操作者==(使用成员变量的正确语法;它比较了显式的参数来隐式this),其一个gr_log比作string。由于您的std::find调用使用字符串作为比较对象,因此您应该很好。

作为替代方案,您可以定义相等操作类之外:

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

注1:inline关键字应该是那里,如果你在一个头文件把这些,但如果你是把他们在一个源文件中。

注2:指定两个运算符函数都允许相等的交换属性。

最后,在此情况下,尚未在哈希不够的 - 成员平等的运营商需要一个参数,非成员平等的运营商需要。