上机内容设计一个类属集合类SET,集合中可以存放不同类型的对象;然后编写一个演示程序利用SET创建并使用整数的集合、字符串的集合以及学生的集合,学生类STUDENT是你自己设计的类类型。(提示:集合中的元素不允许重复,且元素之间是无序的)求c++代码
1条回答 默认 最新
- 「已注销」 2023-06-24 03:42关注
#include <iostream> #include <string> #include <unordered_set> template <typename T> class Set { public: void add(const T& element) { set_.insert(element); } void remove(const T& element) { set_.erase(element); } bool contains(const T& element) const { return set_.find(element) != set_.end(); } void print() const { for (const auto& element : set_) { std::cout << element << ' '; } std::cout << '\n'; } private: std::unordered_set<T> set_; }; class Student { public: Student(const std::string& name, int age) : name_(name), age_(age) {} bool operator==(const Student& other) const { return name_ == other.name_ && age_ == other.age_; } friend std::ostream& operator<<(std::ostream& os, const Student& student); private: std::string name_; int age_; }; std::ostream& operator<<(std::ostream& os, const Student& student) { os << student.name_ << ' ' << student.age_; return os; } namespace std { template <> struct hash<Student> { size_t operator()(const Student& student) const { return hash<string>()(student.name_) ^ hash<int>()(student.age_); } }; } int main() { Set<int> int_set; int_set.add(1); int_set.add(2); int_set.add(3); int_set.print(); Set<std::string> string_set; string_set.add("hello"); string_set.add("world"); string_set.print(); Set<Student> student_set; student_set.add(Student("Alice", 20)); student_set.add(Student("Bob", 21)); student_set.print(); return 0; }解决 无用评论 打赏 举报