我无法理解在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;
}
答案 0 :(得分:10)
设置要求其元素类型以定义小于运算符。见http://www.cplusplus.com/reference/set/set/?kw=set
您可以像这样定义(在成绩定义之后):
bool operator< (const Grade& a, const Grade& b){
return a.id < b.id;
}
答案 1 :(得分: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
}
或者如果你想在结构本身中定义它:
bool operator < ( const Grade& grade2) const
{
return score < grade2.score; // or other method of determining
// if a grade is less than another
}
答案 2 :(得分:6)
如果您重载std::set<Grade>
的{{1}}功能,则可以创建operator<()
。可以使用成员函数或非成员函数来定义函数。
无论采用哪种方法,都必须定义函数,使得LHS和RHS都可以是Grade
个对象。
会员职能方法:
const
非会员职能方法:
struct Grade{
string id;
int score;
bool operator<(Grade const& rhs) const
{
return this->id < rhs.id;
}
};
答案 3 :(得分:2)
感谢大家的帮助,我见过很多解决方案,这是我的代码,它按升序对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;
答案 4 :(得分:-2)
以下是正确编译的更新代码。 &#34;运营商的问题&lt;&#34; for 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;
}