选择集合作为Student类的容器
时间: 2023-08-13 22:09:14 浏览: 45
好的,我明白了。您想在C++中实现一个Student类,并使用集合作为其容器。可以使用STL(标准模板库)中的set或unordered_set来实现。set是一个有序集合,而unordered_set是一个无序集合。具体实现会涉及到定义Student类的成员变量和方法,以及使用集合来存储和管理Student对象。以下是一个示例代码:
```c++
#include <iostream>
#include <set> // 或 #include <unordered_set>
using namespace std;
class Student {
public:
Student(string n, int a) : name(n), age(a) {}
string getName() const { return name; }
int getAge() const { return age; }
bool operator<(const Student& other) const {
return name < other.name;
}
private:
string name;
int age;
};
int main() {
set<Student> students; // 或 unordered_set<Student> students;
students.emplace("Alice", 20);
students.emplace("Bob", 19);
students.emplace("Charlie", 21);
for (const auto& s : students) {
cout << s.getName() << " (" << s.getAge() << ")" << endl;
}
return 0;
}
```
在这个示例中,定义了一个Student类,它有一个姓名和年龄的成员变量,以及一个小于运算符(operator<),用于在集合中比较Student对象的顺序。然后,使用set或unordered_set来存储Student对象,并使用emplace函数来插入新的Student对象。最后,使用范围for循环遍历集合中的Student对象,并输出它们的姓名和年龄。