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;
    }

  • 相关阅读:
    IDEA中classpath
    Java之泛型<T> T与T的用法
    反射机制
    vue mitt 解决多次触发问题
    input限制输入
    解决idea启动端口被占用
    前端压缩图片转base64
    对Bootstrap Table 表格进行封装
    vue项目本地运行
    vue项目搭建
  • 原文地址:https://www.cnblogs.com/donggongdechen/p/9720778.html
Copyright © 2011-2022 走看看