c++模板练习题

// TempleTest.cpp : 此文件包含 "main" 函数。程序执行将在此处开始并结束。
//

#include "pch.h"
#include <iostream>
#include <random>

/*
编写一个程序,使用类模板对数组元素进行排序,倒置、查找和求和
具有对数组元素进行排序,倒置、查找和求和功能,
然后产生类型实参分别为int型和double型的两个模板类,
分别对整型数组与双精度数组完成所要求的操作
*/

using namespace std;
const int SIZE = 100;

template <class Type>
class Array {
private:
	int l, z;
	Type a[SIZE];
public:
	Array(Type *b, int n)
	{
		int i;
		l = n;
		cout << "Array 构造函数:" << endl;
		for (i = 0; i < l; i++) {
			a[i] = b[i];
			cout << a[i] << " ";

		}
		cout << endl;

	}

	void sort();
	void reverse();
	void find(Type t);
	void sum();


};

template <class Type>
void Array<Type>::sort() {
	Type c[SIZE];
	int i, j;
	Type m;
	for (i = 0; i < l; i++) {
		c[i] = a[i];

	}

	// 这下面的{}最好一个都不要省
	// 一个都不省的话 首先方便后期添加代码 其次看起来舒服
	// 排序 升序排序
	for (j = 0; j < l; j++)
	{
		for (i = 0; i < l; i++)
		{
			if (c[i] > c[j])
			{
			    m = c[i];
				c[i] = c[j];
				c[j] = m;
			}
		}
	}

	// 输出排序后的数据 -> a b c
	for (i = 0; i < l; i++)
	{
		cout << c[i] << " ";
	}
	cout << endl;


}

template<class Type>
void Array<Type>::reverse() 
{
	Type c[SIZE];
	Type m;
	int i, j;
	for (i = 0; i < l; i++)
	{
		c[i] = a[i];
	}


		for (j = 0; j < l; j++)
		{
			if (j > (l / 2)) break;
			m = c[j];
			c[j] = c[l-j-1];
			c[l-j-1] = m;
		}
	

	for (i = 0; i < l; i++)
	{
		cout << c[i] << " ";
	}
	cout << endl;


}



int main()
{
    std::cout << "Hello World!\n"; 
	int i,x;
	int *b;
	b = new int[10];
	x = 11;
	//整数
	
	for (i = 0; i < x; i++) {
		b[i] = rand() % 100 +1;
	}
	Array<int> c(b, x);
	c.sort();

	//实数
	//实数随机数
	random_device rd;
	mt19937 gen(rd());
	uniform_real_distribution<> dis(1.0, 2.0);
	double *d;
	d = new double[10];

	for (i = 0; i < x;i++)
	{
		d[i] = dis(gen);
	}

	Array<double> f(d, x);
	f.sort();

	int k;
	cin >> k;

}

// 运行程序: Ctrl + F5 或调试 >“开始执行(不调试)”菜单
// 调试程序: F5 或调试 >“开始调试”菜单

 

  • 0
    点赞
  • 11
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

黑贝是条狗

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值