设计完整程序,由自定义数据类型struct Student{ unsigned ID; string Name; int Score;//…..}的数组stu[]={{1004, "AAAA",90},{1002, "BBBB",80},{1005, "CCCC",85},{1007, "DDDD",75},{1001, "EEEE",65}}生成集合set或multiset或unordered_set等并输出(要求以学号ID为Key)。 说明:要考虑的问题是对自定义数据类型,要按指定key实现元素之间大小关系比较。实现方法有三种: (1)在类型定义中重载运算符<,>,==等; (2)使用自定义仿函数; (3)特化处理less<T>, greater<T>, equal_to<T>等。
时间: 2024-02-15 11:05:54 浏览: 62
下面是使用自定义仿函数实现以学号ID为Key的multiset的完整程序:
```c++
#include <iostream>
#include <string>
#include <set>
using namespace std;
//自定义数据类型
struct Student {
unsigned ID;
string Name;
int Score;
};
//定义仿函数,按ID升序排序
struct StudentLess {
bool operator()(const Student& s1, const Student& s2) const {
return s1.ID < s2.ID;
}
};
int main() {
//定义数组stu
Student stu[] = {
{1004, "AAAA", 90},
{1002, "BBBB", 80},
{1005, "CCCC", 85},
{1007, "DDDD", 75},
{1001, "EEEE", 65}
};
//定义以学号ID为Key的multiset
multiset<Student, StudentLess> stuSet;
//将数组stu中的元素加入stuSet
for (int i = 0; i < 5; i++) {
stuSet.insert(stu[i]);
}
//输出stuSet中的元素
for (auto it = stuSet.begin(); it != stuSet.end(); it++) {
cout << "ID: " << it->ID << ", Name: " << it->Name << ", Score: " << it->Score << endl;
}
return 0;
}
```
输出结果如下:
```
ID: 1001, Name: EEEE, Score: 65
ID: 1002, Name: BBBB, Score: 80
ID: 1004, Name: AAAA, Score: 90
ID: 1005, Name: CCCC, Score: 85
ID: 1007, Name: DDDD, Score: 75
```
阅读全文