栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > C/C++/C#

C++学习日志52----初识模板、函数泛型化、类模板

C/C++/C# 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

C++学习日志52----初识模板、函数泛型化、类模板

目录
  • 一、初识模板
  • 二、函数泛型化
  • 三、类模板


一、初识模板
#include
template
auto add(T x, Q y)
{
	return (x + y);
}
int main()
{
	std::cout << add(3, 2.3) << std::endl;
}


结果如上图所示。

二、函数泛型化
#include
#include"SelectionSort.h"

int main()
{
	double x[]{ 3.0,2.0,8.0,4.0,9.0,1.0,5.0,6.0 };

	for (auto i : x)
	{
		std::cout << i << "  ";
	}
	std::cout << std::endl;

	selectionSort(x,8);

	for (auto i : x)
	{
		std::cout << i << "  ";
	}

	std::cout << std::endl;

	std::array y{ 6.0,2.2,8.5,2.0,8.0,1.0,5.0,6.0 };

	for (auto i : y)
	{
		std::cout << i << "  ";
	}
	std::cout << std::endl;

	selectionSort(y);

	for (auto i : y)
	{
		std::cout << i << "  ";
	}


}

结果如上图所示。

相关文件

template
void selectionSort(std::array&list)
{
	constexpr int size = N;
	//for循环,每次从list[i]~list[size-1]中找出一个最小的数,与list[i]交换
	for (int i = 0; i < size - 1; i++)
	{
		//初始化,将list[i]记为最小值,将i记为最小值的索引
		double min = list[i];
		int index = i;
		//用循环,找出list[i+1]-list[size-1]中的最小值和它的下标
		for (int j = i + 1; j < size; j++)
		{
			if (min > list[j])
			{
				min = list[j];
				index = j;
			}
		}
		//若list[i]不是最小值,那么交换list[i]<-->list[index]
		if (index != i)
		{
			list[index] = list[i];
			list[i] = min;
		}
	}
}

#pragma once
#include
#include
template
void selectionSort(T list[], const std::size_t size)
{
	//for循环,每次从list[i]~list[size-1]中找出一个最小的数,与list[i]交换
	for (int i = 0; i < size - 1; i++)
	{
		//初始化,将list[i]记为最小值,将i记为最小值的索引
		T min = list[i];
		int index = i;
		//用循环,找出list[i+1]-list[size-1]中的最小值和它的下标
		for (int j = i + 1; j < size; j++)
		{
			if (min > list[j])
			{
				min = list[j];
				index = j;
			}
		}
		//若list[i]不是最小值,那么交换list[i]<-->list[index]
		if (index != i)
		{
			list[index] = list[i];
			list[i] = min;
		}
	}
}


三、类模板
#include"Stack.h"
#include
#include
int main()
{
	Stack c;
	std::string s{ "Hello,World!" };
	for (auto i : s)
	{
		c.push(i);
	}
	for (; c.empty() != true;)
	{
		std::cout << c.pop();
	}
}

结果如上图所示。

相关文件

#pragma once
template
class Stack
{
private:
	T elements[100];
	int size{ 0 };
public:
	bool empty();
	T  peek();
	T  push(T value);
	T  pop();
	int getSize();
	Stack();


};

template
Stack::Stack()
{
	size = 0;
	for (auto& i : elements)
	{
		i = 0;
	}
}

template
bool Stack::empty()
{
	return (size == 0 ? true : false);
}

template
int Stack::getSize()
{
	return size;
}

template
T Stack::peek()
{
	return elements[size - 1];
}

template
T Stack::pop()
{
	T temp = elements[size - 1];
	elements[size - 1] = 0;
	size--;
	return temp;
}

template
T Stack::push(T value)
{
	elements[size] = value;
	size++;
	return value;
}

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/869012.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号