2022/4/21 19:33
// ConsoleApplication1.cpp : 定义控制台应用程序的入口点。
//
#include "stdafx.h"
#include
#include
using namespace std;
#if 0
void Print(int* arr, int len);
void Print(double* arr, int len);
//由编译器根据实际调用来生成
template
void travel(T* arr, int len) {
for (int i = 0; i < len; i++) {
cout << arr[i] << " ";
}
cout << endl;
}
int _tmain(int argc, _TCHAR* argv[])
{
int arr[10] = { 1, 2, 3, 4, 5, 6, 7, 8, 9,0 };
double arrD[10] = { 1.1, 2, 3, 4, 5, 6.6, 9, 8, 0,10 };
Print(arr, 9);
Print(arrD, 10);
travel(arr, 10);
while (1);
return 0;
}
void Print(int* arr, int len) {
for (int i = 0; i < len; i++) {
cout << arr[i] << " ";
}
cout << endl << endl;
}
void Print(double* arr, int len) {
for (int i = 0; i < len; i++) {
cout << arr[i] << " ";
}
cout << endl;
}
#endif
#if 0
template
void travel(T* arr, int len) {
for (int i = 0; i < len; i++) {
cout << arr[i] << " ";
}
cout << endl;
}
int main() {
int arr[10] = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 0 };
double arrD[10] = { 1.1, 2, 3, 4, 5, 6.6, 9, 8, 0, 10 };
travel(arrD, 10); //显式传参
travel(arr, 10); //隐式传参
return 0;
}
#endif
#if 0
template
void show(T1 t1, T2 t2) {
cout << t1 << " " << t2 << endl;
}
template
void show1(T1 t1,T1 t2) {
cout << t1 << " " << t2 << endl;
}
int main() {
show(1, 2);
show1(1, 2.2);
return 0;
}
#endif
template
bool compare1(const T& a, const T& b);
template
bool compare2(const T& a, const T& b);
//bool ()(const T& a, const T& b) 函数类型
//函数指针类型 bool (*)(const T& a, const T& b)
template
//传函数指针
void sort(T* arr, int len, bool(*compare)(const T&, const T&));
template
//传函数
void sort1(T* arr, int len, T1 func);
template
void travel(ddd* arr, int len){
for (int i = 0; i < len; i++)
cout << arr[i] << " ";
cout << endl;
}
int _tmain(int argc, _TCHAR* argv[])
{
int arr[10] = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 0 };
double arrD[10] = { 1.1, 2, 3, 4, 5, 6, 7, 8, 9, 0 };
travel(arr, 10);
sort1(arr, 10, compare1);
travel(arr, 10);
sort1(arr, 10, compare2);
travel(arr, 10);
while (1);
return 0;
}
template
void sort1(T* arr, int len, T1 func){
T temp;
for (int i = 0; i < len - 1; i++){
for (int j = 0; j < len - i - 1; j++){
if (func(arr[j], arr[j + 1])){
temp = arr[j];
arr[j] = arr[j + 1];
arr[j + 1] = temp;
}
}
}
}
template
void sort(T* arr, int len,
bool(*compare)(const T&, const T&)){
T temp;
for (int i = 0; i < len - 1; i++){
for (int j = 0; j < len - i - 1; j++){
if ((*compare)(arr[j], arr[j + 1])){
temp = arr[j];
arr[j] = arr[j + 1];
arr[j + 1] = temp;
}
}
}
}
template
bool compare1(const T& a, const T& b){
if (a > b) return true;
else return false;
}
template
bool compare2(const T& a, const T& b){
if (a < b) return true;
else return false;
}
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)