C++使用lamuda表达式和template模板实现堆排序框架

#include <iostream>
#include <algorithm>
#include <functional>
#include <string>

template<typename T>
std::function<void(T *, int, int)> func = [](T *list, int beg, int len) {
	std::function<void(T *, int)> func1 = [](T *list, int len) {
		std::function<void(T[], int, int)> adjust;
		adjust = [&adjust](T * list1, int len, int i) {
			int left = i * 2 + 1, right = i * 2 + 2, max_id = i;

			if (left < len && list1[left] > list1[max_id])
				max_id = left;
			if (right < len && list1[right] > list1[max_id])
				max_id = right;

			if (max_id != i)
			{
				std::swap(list1[max_id], list1[i]);
				adjust(list1, len, max_id);
			}
		};

		for (int i = len / 2 - 1; i >= 0; i--)
		{
			adjust(list, len, i);
		}

		for (int i = len - 1; i >= 0; i--)
		{
			std::swap(list[0], list[i]);
			adjust(list, i, 0);
		}
	};
	func1(&list[beg], len);
};

class abc
{
public:
	std::string f1;
	int f2;
	float f3;

};
bool operator > (abc const&x1, abc const&x2)
{
	if (x1.f1 > x2.f1)
		return true;
	else
		return false;
}
int main()
{
	
	int a[11] = {8,6,1,3,45,89,15,7,98,15,68 };
	func<int>(a, 0, 11);
	for (auto s : a)
	{
		std::cout << s << " ";
	}

	std::cout << std::endl;
	double b[6] = { 9.1, 86.2, 63.1, 78.2, 15.6, 115.3 };
	func<double>(b, 0, 6);
	for (auto s : b)
	{
		std::cout << s << " ";
	}

	std::string str[5] = { "hg","is","bhi","ad","gfi" };
	std::cout << std::endl;
	func<std::string>(str, 0, 5);
	for (auto s : str)
	{
		std::cout << s << " ";
	}


	abc str1[5] = { {"asd", 77, 86.4}, {"gfhg", 3, 12.42}, {"qwe", 89, 56.7}, {"mgf", 64, 78.5}, {"oas", 23, 55.6}};
	func<abc>(str1, 0, 5);
	for (abc x : str1)
	{
		std::cout << x.f1 << " " << x.f2 << " " << x.f3 << std::endl;
	}
}

猜你喜欢

转载自blog.csdn.net/hao_san_520/article/details/86590569
今日推荐