单纯而又简单的练习,已经睁不开眼了。
#include <iostream>
#include <algorithm>
using namespace std;
class student{
public:
struct node {
string name;
long long nums;
int score;
bool operator<(const node& a)const {
return a.nums>nums;
}
};
student(int n = 0) {
p = new node[n];
temp = new node[n];
len = 0;
}//构造函数
bool cmp(node x, node y) {
return x.score < y.score;
}
void xinxi(long long n, string m, int w);
void shuchu();
void chaxun(int n);
node* p_get() {//得到p,因为你的p是私有的所以需要开一个接口调用,下面的len也是同理
return p;
}
int len_get() { return len; }
private:
node* p;
node* temp;
int len = 0;
};
void student::xinxi(long long n, string m, int w) {
len++;
temp = new node[len];//开辟新的内存空间
for (int i = 0; i < len - 1; i++) {//全靠昨天葛葛的教诲
temp[i].name = p[i].name;
temp[i].nums = p[i].nums;
temp[i].score = p[i].score;
}
temp[len - 1].nums = n;
temp[len - 1].name = m;
temp[len - 1].score = w;
p = temp;
}
void student::shuchu() {
for (int i = 0; i < len; i++) {
cout << "学号:" << p[i].nums << "\t" << "姓名:" << p[i].name << "\t" << "成绩:" << p[i].score << endl;
}
}
void student::chaxun(int n) {
int ans = -1;
int l = 0;
int r = len;
while (l <= r) {//就这事,葛葛非要我写个二分。当然要上我的万能模板了
int mid = (l + r) / 2;
if (p[mid].nums == n) {
ans = mid;
break;
}
else if (p[mid].nums < n) {
l = mid + 1;
}
else {
r = mid - 1;
}
}
if (ans != -1) {
cout << "该同学存在" << endl;
cout << "姓名为:" << p[ans].name << " " << "成绩为:" << p[ans].score << endl;
}
else {
cout << "不存在" << endl;
}
}
void menu();
void input();
void output();
void lookup();
void cuowu();
student arr;
int main()
{
int n = -1;
void menu();
while(n!=4) {
menu();
cin >> n;
switch(n)
{
case 1:input(); break;
case 2:output(); break;
case 3:lookup(); break;
default:cuowu();break;
}
}
}
void menu() {
cout << "输入1添加学生信息" << endl;
cout << "输入2打印成绩表" << endl;
cout << "输入3通过学号查询学生信息" << endl;
cout << "输入4结束程序" << endl;
}
void input() {
long long x; string y; int z;
cout << "请输入学生学号:";
cin >> x;
cout << "请输入学生姓名:";
cin >> y;
cout << "请输入学生成绩:";
cin >> z;
arr.xinxi(x, y, z);
}
void output() {
sort(arr.p_get(), arr.p_get() + arr.len_get());
arr.shuchu();
}
void lookup() {
sort(arr.p_get(), arr.p_get() + arr.len_get());
int m;
cout << "请输入您要查找的学号:";
cin >> m;
arr.chaxun(m);
cout << endl;
}
void cuowu() {
cout << "您输入的数字错误,请重新输入!" << endl;
}
撒花!睡觉。