m0_56773044 2021-05-25 22:20 采纳率: 0%
浏览 24

类属机制设计类属集合

上机内容设计一个类属集合类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;
    }
    
    
    评论

报告相同问题?

悬赏问题

  • ¥15 安卓adb backup备份应用数据失败
  • ¥15 eclipse运行项目时遇到的问题
  • ¥15 关于#c##的问题:最近需要用CAT工具Trados进行一些开发
  • ¥15 南大pa1 小游戏没有界面,并且报了如下错误,尝试过换显卡驱动,但是好像不行
  • ¥15 没有证书,nginx怎么反向代理到只能接受https的公网网站
  • ¥50 成都蓉城足球俱乐部小程序抢票
  • ¥15 yolov7训练自己的数据集
  • ¥15 esp8266与51单片机连接问题(标签-单片机|关键词-串口)(相关搜索:51单片机|单片机|测试代码)
  • ¥15 电力市场出清matlab yalmip kkt 双层优化问题
  • ¥30 ros小车路径规划实现不了,如何解决?(操作系统-ubuntu)