实现目标
1.将sort排序函数模板化
2.输入两种类型的数组(stl的array,普通数组),分别排序后打印输出
GenericSort.h
#pragma once
#include<iostream>
#include<array>
//模板声明和实现一起放在头文件
//选择排序法
template<typename T>
void selectionSort(T list[], const size_t size) {
for (int i = 0; i < size - 1; i++) {
T min = list[i];
size_t index = i;
for (int j = i + 1; j < size; j++) {
if (min > list[j]) {
min = list[j];
index = j;
}
}
if (i != index) {
list[index] = list[i];
list[i] = min;
}
}
}
//模板声明和实现一起放在头文件
//选择排序法
template<typename T,const size_t N>
void selectionSort(std::array<T, N>&list) {
constexpr int size_m = N;
for (int i = 0; i < size_m - 1; i++) {
T min = list[i];
size_t index = i;
for (int j = i + 1; j < size_m; j++) {
if (min > list[j]) {
min = list[j];
index = j;
}
}
if (i != index) {
list[index] = list[i];
list[i] = min;
}
}
}
TestGenericSort.cpp
#include<iostream>
using namespace std;
#include "GenericSort.h"
int main() {
char list[]{ 'a','d','b','e','c' };
for (auto i : list) {
cout << i << " ";
}
cout << endl;
selectionSort(list, sizeof(list) / sizeof(list[0]));
for (auto i : list) {
cout << i << " ";
}
cout << endl;
std::array<double, 5> arr{ 1.0,4.0,9.0,3.0,6.0 };
for (auto i : arr) {
cout << i << " ";
}
cout << endl;
selectionSort(arr);
for (auto i : arr) {
cout << i << " ";
}
}
运行窗口: