运算符重载之 []

函数 operator[] 可以用于为类的对象定义下标运算的意义。

operator[] 的第二个参数(下标)可以具有任何类型,这就使得我们可以去定义vector ,关联数组(仿写map)。


eg:
用运算符重载的方式来进行词频统计,我们仿写一个关联数组:

class Assoc {
public:
    Assoc() {}
    const double& operator[](const std::string &n);
    double& operator[](std::string &n); 
    //注意这里返回的是 & 引用,可以修改! 
    void print_all() const;
private:
    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 &elem);    //forbidden
    Assoc& operator=(const Assoc &elem); //forbidden
};

//这里等价于简单实现了map的 [] 操作
double& Assoc::operator[](std::string &n)
{
    for (std::vector<Pair>::iterator i = vec.begin(); i != vec.end(); i++)
        if (i->name == n)
            return i->val;
    vec.push_back(Pair(n, 0));
    return vec.back().val;
}

total:

#include <iostream>
#include <vector>

class Assoc {
public:
    Assoc() {}
    const double& operator[](const std::string &n);
    double& operator[](std::string &n);
    void print_all() const;
private:
    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 &elem);       //forbidden
    Assoc& operator=(const Assoc &elem);
};

double& Assoc::operator[](std::string &n)
{
    for (std::vector<Pair>::iterator i = vec.begin(); i != vec.end(); i++)
        if (i->name == n)
            return i->val;
    vec.push_back(Pair(n, 0));
    return vec.back().val;
}
const double& Assoc::operator[](const std::string &n)
{
    for (std::vector<Pair>::iterator i = vec.begin(); i != vec.end(); i++)
        if (i->name == n)
            return i->val;
    vec.push_back(Pair(n, 0));
    return vec.back().val;
}
void Assoc::print_all() const
{
    for (auto it = vec.begin(); it != vec.end(); it++)    
        std::cout<<it->name<<" : "<<it->val<<std::endl;
}

int main()
{
    Assoc obj;
    std::string temp;
    while (std::cin >> temp)
        obj[temp]++;

    obj.print_all();
    return 0;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值