Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

This sample code won't compile

Tags:

c++

I cannot understand the error message I get when I compile this code in a cygwin shell. The message is very long, but somewhere in the middle of this 1,000 line error it says:

no matching call for operator <

What does this mean? Here's my code:

#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;
}
like image 731
XDProgrammer Avatar asked Jul 03 '15 03:07

XDProgrammer


1 Answers

Sets require their element type to define the less than operator. See http://www.cplusplus.com/reference/set/set/?kw=set

You could define it like this (after the definition of Grade):

bool operator< (const Grade& a, const Grade& b){
    return a.id < b.id;
} 
like image 79
qbt937 Avatar answered Oct 05 '22 00:10

qbt937