此示例代码无法编译

This sample code won't compile

本文关键字:编译 代码      更新时间:2023-10-16

我无法理解在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;
}

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

你可以这样定义它(在等级定义之后(:

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

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

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
}

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

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

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

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

成员功能方法:

struct Grade{
   string id;
   int score;
   bool operator<(Grade const& rhs) const
   {
      return this->id < rhs.id;   
   }
}; 

非成员函数方法:

struct Grade{
   string id;
   int score;
}; 
bool operator<(Grade const& lhs, Grade const& rhs)
{
   return lhs.id < rhs.id;   
}

感谢大家的帮助,我看到了很多解决方案,这是我的代码,它按升序对ID进行排序

#include <iostream>
#include <string>
#include <set>
#include <algorithm>
#include <iterator>
using namespace std;
struct Grade{
 string id;
 int score;
 bool operator< (const Grade& g) const {
    return this->id < g.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 << endl;; 
    return 0;

这是正确编译的更新代码。std::set的"operator<"问题已解决:

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