c++类模版和运算符重载的运用

最近在看数据结构算法c++描述,很久没写c++了,所以就当回忆下,所以以下代码就当练手,输出的是工资的最大值人的姓名和它的工资:

#include<iostream>
#include<vector>
#include<string>
using namespace std;

template <typename Compareable> //模版
const Compareable & findMax(const vector<Compareable> & arr) //Compareable可以表示任意类型,这里是表示Employee类
{
    int maxIndex = 0;
    for(int i=1; i<arr.size(); i++)
    {
        if(arr[maxIndex] < arr[i])
        {
            maxIndex = i;
        }
    }
    return arr[maxIndex];
}
class Employee //雇员的类
{
public:
    void setVaule(const string & n,double s) //构造函数初始化,两个参数
    {
        name = n;
        salary = s;
    }
    const string & getName() const //返回员工的姓名
    {
        return name;
    }
    void print(ostream &out) const //要输出的东西
    {
        out << name << "(" << salary << ")";
    }
    bool operator < (const Employee & rhs) const //运算符重载
    {
        return salary < rhs.salary;
    }
private:
    string name;
    double salary;
};
ostream & operator << (ostream &out,const Employee & rhs) //输出流
{
    rhs.print(out); 
    return out;
}
int main()
{
    vector<Employee> v(3); //vector数组,表示容器内有三个vaule
    v[0].setVaule("George Bush",400000.00);
    v[1].setVaule("Bill Gates",20000000.00);
    v[2].setVaule("Dr.Phil",130000000.00);
    cout<<findMax(v)<<endl; //如果没有用输出流的话,那么这句会报错
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值