essentialc++ 2.5练习个人解决方案

 

写这个练习花了不少时间

要理解好题目的意思

#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
//大意就是通过一系列的小函数实现max的功能
//本题的重要是理解重载函数:C++中,在同一作用域下,形参列表不同的同名函数构成重载关系,且不会冲突。
//所以题目就是让你构建多个不同的同名函数来实现不同参数的一个函数比大小
//关于怎么测试我们可以比较同一类型的数组和容器

//部分1,两个个数的最大值
inline int max(int a,int b) 
{
    return (a > b ? a : b);
}
inline float max(float a, float b)
{
    return(a > b ? a : b);
}
inline string max(string a, string b)
{
    return(a > b ? a : b);
}


//部分2,容器的最大值
vector<int>A = { 1,2,3,4,5 };
inline int max(vector<int>& A) 
{
    return(*max_element(A.begin(), A.end()));//注意这里的max_element函数没有*返回的是地址,有*返回的是这个地址上的值
}
vector <float>B = { 6,7,8,9,10 };
inline float max(vector<float>&B) 
{
    return(*max_element(B.begin(), B.end()));
}
vector <string>C = { "a","b","c","d","e"};
inline string max(vector<string>) 
{
    return(*max_element(C.begin(), C.end()));
}

//部分3,数组的最大值
int arr1[5] = { 11,12,13,14,15 };
inline int max(int *p,int num) //注意这个传递的是数组的首地址,我真的被坑死
{
    return(*max_element(p, p + 5));//用p清晰的多,一开始这里我用(arr1,arr1+5)这个时候就要注意arr1是参数列表int &arr1中的arr1是变量,如果是int* arr1那么arr1就是数组首位地址   
    //int &a = arr会报错,参数传递这样传也不行,应该是不能应用地址,只能int &a = arr[3],,这个时候你可以选择int &p=arr1[0],max_element里用&p
    //关于p为什么么是加5,我只能说p+0和p+1地址是一样的,
}
float arr2[5] = { 16,17,18,19,20 };
inline float max(float* p, int num) 
{
    return(*max_element(p, p + 5));
}
string arr3[5] = { "f","h","i","j","k" };
inline string max(string* p, int num) 
{
    return(*max_element(p, p + 5));
}
int main(){
    cout<<max(max(A), max(arr1, 5))<<endl;//max(容器最大的,数组最大的)
    cout<<max(max(B), max(arr2, 5))<<endl;
    cout<<max(max(C), max(arr3, 5));

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值