operator[] 重载

时间:2023-03-09 00:30:38
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;
}