C++模板练习题

1:Swap函数

template<class T>
void Swap(T &a, T &b)
{
	T temp = a;
	a = b;
	b = temp;
}

2 :输入输出排序


template<class T>
void  Sort(T arr[], int len)
{
	int i, j;
	T tmp;
	for (i = 0; i < len - 1; i++)
	{
		for (j = 0; j < len - 1-i; j++)
		{
			if (arr[j] > arr[j + 1])
			{
				tmp = arr[j];
				arr[j] = arr[j + 1];
				arr[j + 1] = tmp;
			}
		}
	}
}


template<class T>
void Output(T arr[], int len)
{
	int i;
	for (i = 0; i < len; i++)
	{
		if (i < len - 1)
		{
			cout << arr[i] << ", ";
		}
	
	}
	cout << arr[len - 1]<< endl;
}

template<class T>
void Input(T arr[], int len)
{
	for (int i = 0; i < len; i++)
	{
		cin >> arr[i];
	}

}
int main()
{
	const int LEN = 5;
	int type;
	while (std::cin >> type)
	{
		switch (type)
		{
		case 0:
		{
			int a1[LEN];
			Input<int>(a1, LEN); Sort<int>(a1, LEN); Output<int>(a1, LEN);
			break;
		}
		case 1:
		{
			char a2[LEN];
			Input(a2, LEN); Sort(a2, LEN); Output(a2, LEN);
			break;
		}
		case 2:
		{
			double a3[LEN];
			Input(a3, LEN); Sort(a3, LEN); Output(a3, LEN);
			break;
		}
		}
	}
	system("pause");
	return 0;
}

在这里插入图片描述

3:Search


#include<iostream>
#include<string.h>
#include<fstream>
#include<string>
#include <algorithm>
using namespace std;

template <class T>
int Search(const T * array, int arrayLen, const T & value)
{
	
	for (int i = 0; i < arrayLen; i++)
	{
		if (array[i] == value)
		{
			return i;
		}

	}

	return -1;
}

int main()
{
	int n;
	std::cin >> n;
	int *nValues = new int[n];
	for (int i = 0; i < n; i++)
	{
		std::cin >> nValues[i];
	}
	int d;
	std::cin >> d;
	std::cout << Search(nValues, n, d) << std::endl;
	delete[] nValues;

	double f;
	std::cin >> n;
	double *dValues = new double[n];
	for (int i = 0; i < n; i++)
	{
		std::cin >> dValues[i];
	}
	std::cin >> f;
	std::cout << Search(dValues, n, f) << std::endl;
	delete[] dValues;

	std::cin >> n;
	char *cValues = new char[n];
	for (int i = 0; i < n; i++)
	{
		std::cin >> cValues[i];
	}
	char c;
	std::cin >> c;
	std::cout << Search(cValues, n, c) << std::endl;
	delete[] cValues;

	return 0;
}
  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值