zoukankan      html  css  js  c++  java
  • operator[] 重载

    #include <iostream>
    #include <vector>
    #include <string>

    class Assoc {
        struct Pair {
            std::string name;
            double val;
            Pair(std::string n="", double v=0) :name(n), val(v) {}
        };
        std::vector<Pair> vec;

        Assoc(const Assoc&);
        Assoc& operator=(const Assoc&);
    public:
        Assoc() {}
        const double& operator[] (const std::string&);
        double& operator[] (std::string&);
        void print_all() const;
    };

    double& Assoc::operator[] (std::string& s) {
        for(std::vector<Pair>::iterator p=vec.begin();p!=vec.end();++p) {
            if (s == p->name)
                return p->val;
        }
        vec.push_back(Pair(s,0));
        return vec.back().val;
    }

    void Assoc::print_all() const {
        for(std::vector<Pair>::const_iterator p=vec.begin();p!=vec.end();++p) {
            std::cout<<p->name<<": "<<p->val<<std::endl;
        }
    }

    int main() {
        std::string buf;
        Assoc vec;
        while(std::cin>>buf && buf!="end")
            vec[buf]++;
        vec.print_all();

        return 0;
    }

  • 相关阅读:
    面向对象程序设计第五次作业(修改)
    C++作业 一
    面向对象程序设计第四次作业
    面向对象程序设计第三次作业
    C++学习笔记3
    C++学习笔记2
    C++学习笔记1
    面向对象程序设计作业二
    面向对象程序设计第二次作业
    随笔
  • 原文地址:https://www.cnblogs.com/donggongdechen/p/9720778.html
Copyright © 2011-2022 走看看