此示例代码将无法编译

XDP*_*mer 5 c++

我无法理解在cygwin shell中编译此代码时收到的错误消息.消息很长,但在这1000行误差的中间某处说:

没有匹配的运营商呼叫<

这是什么意思?这是我的代码:

#include <iostream>
#include <string>
#include <set>
#include <algorithm>
#include <iterator>

using namespace std;

struct Grade{
 string id;
 int score;

  bool operator() (Grade& a, Grade& b){
        return a.id < b.id;   
    } 
};  

int main()
{   
    Grade g;
    set<Grade> gs;

    g.id = "ABC123";
    g.score = 99;
    gs.insert(g);

    g.id = "BCD321";
    g.score = 96;
    gs.insert(g);

    for(auto it : gs)
        cout << it.id << "," << it.score;

    return 0;
}
Run Code Online (Sandbox Code Playgroud)

qbt*_*937 10

集需要其元素类型来定义小于运算符.请参阅http://www.cplusplus.com/reference/set/set/?kw=set

你可以像这样定义它(在Grade的定义之后):

bool operator< (const Grade& a, const Grade& b){
    return a.id < b.id;
} 
Run Code Online (Sandbox Code Playgroud)


Ale*_*dro 7

std::set以排序顺序存储其元素,这要求其元素类型为其operator <定义.在这种情况下,您需要operator <为您的Grade类型定义.

bool operator < (const Grade& grade1, const Grade& grade2)
{
   return grade1.score < grade2.score;  // or other method of determining
                                        // if a grade is less than another
}
Run Code Online (Sandbox Code Playgroud)

或者,如果您想在结构本身中定义它:

bool operator < ( const Grade& grade2) const
{
    return score < grade2.score;  // or other method of determining
                                    // if a grade is less than another
}
Run Code Online (Sandbox Code Playgroud)


R S*_*ahu 6

std::set<Grade>如果重载operator<()函数,可以创建一个Grade.可以使用成员函数或非成员函数来定义函数.

无论采用哪种方法,都必须定义函数,使得LHS和RHS都可以是const对象.

会员职能方法:

struct Grade{
   string id;
   int score;

   bool operator<(Grade const& rhs) const
   {
      return this->id < rhs.id;   
   }
}; 
Run Code Online (Sandbox Code Playgroud)

非会员职能方法:

struct Grade{
   string id;
   int score;
}; 

bool operator<(Grade const& lhs, Grade const& rhs)
{
   return lhs.id < rhs.id;   
}
Run Code Online (Sandbox Code Playgroud)


Mit*_*ora -2

这是可以正确编译的更新后的代码。“operator<”的问题std::set已解决:

#include <iostream>
#include <string>
#include <set>
#include <algorithm>
#include <iterator>

using namespace std;

struct Grade{
   string id;
   int score;

    bool operator<(const Grade& that) const
    {
        return this->score < that.score;   
    } 

    bool operator() (Grade& a, Grade& b){
        return a.id < b.id;   
    } 
};  

int main() {
    Grade g;
    set<Grade> gs;

    g.id = "ABC123";
    g.score = 99;
    gs.insert(g);

    g.id = "BCD321";
    g.score = 96;
    gs.insert(g);

    for(auto it : gs)
        cout << it.id << "," << it.score;

    return 0;
}
Run Code Online (Sandbox Code Playgroud)

  • 这里字符串的比较没有问题。`operator&lt;` 在包含的 `&lt;string&gt;` 中定义。唯一的问题是这里缺少“Grade”的“operator&lt;”。 (3认同)