题目:输入10个学生的学号和对应成绩 按成绩的从小到大排列 并用一个有序链表连接起来
想法:
1.map按照key值排大小(由于成绩可能是一样的,学号一定是相异的,所以要采用map的话,键值key一定是学号,值一定是成绩)
#include<stdio.h>
#include<map>
#include<iostream>
using namespace std;
int main() {
map<int, int> mp;
mp[30] = 20;
mp[20] = 30;
mp[10] = 40;
for (map<int, int>::iterator it = mp.begin();
it != mp.end(); it++) {
cout << it->first <<' '<< it->second << endl;
}
return 0;
}
2.想利用sort 来对map的值进行排序 发现不可行 麻烦
于是转用vector来进行排序(针对vector的第二个位置的数(第一个位置为学号,第二个位置为成绩),按照从小到达的顺序)
排序法则函数cmp如下:
bool cmp(const vector<int>& arr1,const vector<int>& arr2)
{
return arr1[1] < arr2[1];
}
3.定义一个二维数组(示例如下)
[
[3,11]
[4,11]
[5,9]
]
int m, n; //m记录学生的学号 n记录学生的成绩
vector<vector<int>> vec;
int count = 10;
while (count > 0)
{
cin >> m >> n;
vector<int>vec1 = {m,n};
vec.push_back(vec1);
count--;
}
sort(vec.begin(), vec.end(), cmp);//调用排序算法
4.定义链表
struct ListNode {
int index; //listnode里面数值域有两个值 并不能直接拿vector<int>vec 来指代数据域 分为两个int值
int grade;
ListNode* next;
};
5.整体的代码实现
#include<map>
#include<iostream>
#include<vector>
#include<algorithm>
using namespace std;
struct ListNode {
int index; //listnode里面数值域有两个值 并不能直接拿vector<int>vec 来指代数据域 分为两个int值
int grade;
ListNode* next;
};
bool cmp(const vector<int>& arr1,const vector<int>& arr2)
{
return arr1[1] < arr2[1];
}
int main()
{
int m, n; //m记录学生的学号 n记录学生的成绩
vector<vector<int>> vec;
int count = 10;
while (count > 0)
{
cin >> m >> n;
vector<int>vec1 = {m,n};
vec.push_back(vec1);
count--;
}
sort(vec.begin(), vec.end(), cmp);
/*while (count <10)
{
cout << vec[count][0] << ' ' << vec[count][1] << endl;
count++;
}*/
ListNode* node = new ListNode();
ListNode* head = node;
node->index = vec[0][0];
node->grade = vec[0][1];
while (count < 9)
{
ListNode* node1 = new ListNode();
node1->index = vec[count+1][0];
node1->grade = vec[count+1][1];
count++;
node->next = node1;
node = node->next;
}
node->next = NULL;
node = head;
while (node!= NULL)
{
cout << node->index << ' ' << node->grade << endl;
node = node->next;
}
}