继上一小结 修改测试用例
这个template 还是有东西 的 可以自定义
#ifndef SELECTIONSORT_STUDENT_H
#define SELECTIONSORT_STUDENT_H
//解决ide.h文件的多重引用的问题
#include <iostream>
#include <string>
using namespace std;
struct Student
{
/* data */
string name;
int score;
//为了可以直接进行student的比较,这里需要运算符的重载
bool operator<(const Student &otherStudent){
return score != otherStudent.score ? score < otherStudent.score : name < otherStudent.name;
}
//为了打印输出结果,还需要对<<进行重载
friend ostream& operator<<(ostream &os, const Student &student){
os<<"Student: "<<student.name<<" "<<student.score<<endl;
return os;
}
};
#endif //SELECTIONSORT_STUDENT_H
使用
#include<iostream>
#include<string>
#include "Student.h"
using namespace std;
template<typename T >
void selectionSort( T arr[], int n){
for(int i = 0 ; i < n ; i++){
//寻找【i,n之间的最小值】
int minIndex = i;
for( int j = i + 1 ; j < n ; j++)
if(arr[j] < arr[minIndex] )
minIndex = j;
swap( arr[i] , arr[minIndex]);
}
}
int main()
{
int a[5] = {5,62,3,58,44};
selectionSort( a, 5 );
for( int i = 0 ; i < 5 ; i++)
cout<<a[i]<< " ";
cout<<endl;
float b[4] = {4.4,2.3,5.63};
selectionSort( b , 3);
for( int i = 0 ; i < 3 ; i++)
cout<<b[i]<< " ";
cout<<endl;
string c[2] = {"z","b"};
selectionSort( c , 2);
for( int i = 0 ; i < 2 ; i++)
cout<<c[i]<< " ";
cout<<endl;
Student d[3] = {{"D",90} , {"C",89} , { "B", 114}};
selectionSort( d , 3);
for( int i = 0 ; i < 3 ; i++)
cout<<d[i];
cout<<endl;
return 0;
}