因此,我的代码基本上将学生ID和姓名映射到他或她的成绩和许多功能,并包含内部功能,允许您按年级,ID等搜索特定学生。
我试图实现的一个特殊功能是按降序打印所有输入学生的成绩。
#include <iostream>
#include <string>
#include <algorithm>
#include <map>
#include <vector>
using namespace std;
class student{
public:
student();
student(int,string);
int id;
string name;
};
class table{
public:
void InsertStudent(student x, int y);
void PrintAll(table t);
void SearchbyID(student x);
void SearchbyGrade(int y);
void SortbyGrade(table t);
private:
map<student, int > records;
};
int main (){
table t;
string command;
int id;
string name;
int grade;
student x;
while ( cin >> command ){
if (command=="InsertStudent"){
cin >> id >> name>> grade;
student s(id,name);
t.InsertStudent(s,grade);
}else if (command == "PrintAll"){
t.PrintAll(t);
}else if (command == "SearchbyID"){
cin >> x.id;
t.SearchbyID(x);
}else if (command == "SearchbyGrade"){
cin >> grade;
t.SearchbyGrade(grade);
}
else if (command == "SortbyGrade"){
t.SortbyGrade(t);
}
else if (command == "exit"){
return 0;
}
}
}
为简化相同,我包括以下结构。
struct information{
string id;
string name;
string grade;
};
void table::SortbyGrade(table t){
map<student,int>::iterator itr;
information a;
vector<information> v;
for(itr=records.begin();itr!=records.end();itr++)
{
a.id=(*itr).first.id;
a.name=(*itr).first.name;
a.grade=(*itr).second;
v.push_back(a);
}
vector<information>::iterator itr2;
sort(v.begin(),v.end(),compare);
for(itr2=v.begin();itr2!=v.end();itr2++){
cout<<(*itr2).id<<" "<<(*itr2).name<<" "<<(*itr2).grade<<endl;
}
}
在这段代码中,我基本上将关键点和地图上的值复制到向量上以实现排序算法
bool compare(const information &a, const information & b){
if(a.grade>b.grade)
return true;
else if(a.grade<b.grade)
return false;
else
return a.id<b.id;
}
输入
InsertStudent 2016001 David 97
InsertStudent 2016002 Alice 88
InsertStudent 2016003 Jackson 100
InsertStudent 2016004 Eric 60
InsertStudent 2016005 John 97
InsertStudent 2016006 Michael 79
输出
Jackson d
David a
John a
Alice X
Michael O
埃里克这表示正在正确执行排序,但信息似乎已被更改。
答案 0 :(得分:2)
我为您创建了一个重现行为的最小示例:
#include <string>
#include <iostream>
int main() {
std::string s;
s = 100;
std::cout << s << std::endl;
}
在你进一步阅读之前,你能否自己找出原因?
std::string::operator=
有一些重载,而这里最适合的是std::string::operator=(char ch)
。 100是'd'
的ASCII代码,因此当您将其值分配给string grade
结构中的information
时,这就是杰克逊的成绩。