FunctionTemplate

//FunctionTemplate.cpp

#include <iostream>
#include <string>
using std::string;
using std::cout;
using std::cin;
using std::endl;

struct stu
{
	string name;
	double score;
};

template <typename T>
void swap(T& x,T& y);

template <typename T1,typename T2>
auto get(T1 x,T2 y) ->decltype(x+y);

stu& operator+(stu& s1,stu& s2);


int main()
{
	int a=1,b=2;
	double c=1.1,d=2.2;
	stu s1={"fyj",100},s2={"jyf",90};
	swap(a,b);
	swap(c,d);
	swap(s1,s2);
	cout << a << "," << b << endl
		 << c << "," << d << endl
		 << s1.name << "," << s1.score << endl
		 << s2.name << "," << s2.score << endl;
	cout << get(a,c) << endl
		 << get(b,d) << endl
		 << (s1+s2).name << "," << (s1+s2).score << endl;
	while(cin.get()!='\n');
	return 0;
}

template <typename T>
void swap(T& x,T& y)
{
	T temp=x;
	x=y;
	y=temp;
}

template <typename T1,typename T2>
auto get(T1 x,T2 y) ->decltype(x+y)
{
	decltype(x+y) z=x+y;
	return z;
}

stu& operator+(stu& s1,stu& s2)
{
	s1.name="haha";
	s1.score=s1.score+s2.score;
	return s1;
}

Sure, here is a sorting function template in C++: ```c++ #include <iostream> #include <vector> #include <string> #include <algorithm> template <typename T> void sortVector(std::vector<T>& vec) { std::sort(vec.begin(), vec.end()); } int main() { std::vector<int> intVec = {3, 1, 4, 2, 5}; std::vector<float> floatVec = {3.5, 1.2, 4.1, 2.0, 5.7}; std::vector<std::string> stringVec = {"apple", "banana", "car", "dog", "elephant"}; std::cout << "Before sorting:" << std::endl; for (auto i : intVec) std::cout << i << " "; std::cout << std::endl; for (auto f : floatVec) std::cout << f << " "; std::cout << std::endl; for (auto s : stringVec) std::cout << s << " "; std::cout << std::endl; sortVector(intVec); sortVector(floatVec); sortVector(stringVec); std::cout << "After sorting:" << std::endl; for (auto i : intVec) std::cout << i << " "; std::cout << std::endl; for (auto f : floatVec) std::cout << f << " "; std::cout << std::endl; for (auto s : stringVec) std::cout << s << " "; std::cout << std::endl; return 0; } ``` This function template takes a vector of any type `T` and sorts it using the `std::sort` function from the `<algorithm>` header. The main function creates three vectors of different types (integer, floating point, and string), fills them with some values, prints them before sorting, sorts them using the `sortVector` function template, and then prints them again after sorting. You can compile and run this program to see the sorting in action. The output should look something like this: ``` Before sorting: 3 1 4 2 5 3.5 1.2 4.1 2 5.7 apple banana car dog elephant After sorting: 1 2 3 4 5 1.2 2 3.5 4.1 5.7 apple banana car dog elephant ```
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值