⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 templateplus.cpp

📁 我学习C++ Primer Plus过程中写下的课后作业的编程代码
💻 CPP
字号:
// 6.编写模板函数maxn(),它将由一个T类型元素组成的数组和一个表示数组
// 元素数目的整数作为参数,并返回数组中最大的元素。在程序对它进行测
// 试,该程序使用一个包含6个int元素的数组和一个包含4个double元素的数
// 组来调用该函数。程序还包含一个具体化,它将char指针数组和数组中的
// 指针数量作为参数,并返回最长的字符串的地址。如果有多个这样的字符
// 串,则返回其中第一个字符串的地址。使用由5个字符串指针组成的数组来
// 测试该具体化。

#include <iostream>
#include <cstring>

// 因为我在这多加了个const 
// T maxn( const T arr[],int arrSize)
// 我忙了一下午,哪为什么我第5题又可以用呢?
// 是因为有了下面的模板具体化
template <typename T>
T maxn(const T arr[], int arrSize); 

template<> const char* maxn(const char* arr[],int arrSize); 
//模板具体化与普通的函数重载又有何区别?何必多此一举呢?

int main()
{
	using namespace std;
	int int_arr[6] = {53, 56, 75, 32, 47, 86};
	double dou_arr[4] = {62.4, 666.2, 74.2, 677.3};
	const char* char_arr[5] = {
		"I love you",
			"be with you",
			"a good boy",
			"you are wonderful!",
			"yes I am"
	};
	cout<<"The max integer of array is: "<<maxn(int_arr,6)<<endl;
	cout<<"The max double of array is: "<<maxn(dou_arr,5)<<endl;
	cout<<"The max string of array is: "<<maxn(char_arr,5)<<endl;
	return 0;
}

template <typename T>
T maxn(const T arr[], int arrSize)
{
	T bigIndex = arr[0];		//子表中最大元素的下标
	int i;	
	for(i = 1; i < arrSize; i++)
	{
		if(arr[i] > bigIndex)
			bigIndex = arr[i];
	}	
	return bigIndex;
}

template<> const char* maxn(const char* arr[],int arrSize)
{	
	const char* max = arr[0];      //为什么const char* max 在下面还能被赋值?	
	int i;	
	for(i = 1; i < arrSize; i++)
	{
		if( strlen(arr[i]) > strlen(max) ) 
		{
//这里const char * max 是不是指:max指向const单元的指针.而指针本身可以为左值
			max = arr[i];           
		}
	}
	return max;
}


⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -