c++ STL---selectionSort improvement

使用c++的模板函数库中的库函数,外加自己书写的辅助函数进行选择排序的测试。

可以自己创建一个.h文件,文件中书写自己可能用的到的方法,在此我书写了一个结构体函数,和输出函数的.h文件,来帮助我完成selectionSort函数的测试。

//student.h file

//宏定义  为了解决.h文件的多重引用问题 
#ifndef SELECTIONSORT_SORTTESTHELPER_H
#define SELECTIONSORT_SORTTESTHELPER_H

#include 
#include 

using namespace std;

namespace student{
struct Student{
    string name;
    int score;
    
    bool operator< (const Student &otherStudent) {
//      return score < otherStudent.score;//分数按照从小到大进行比较 
//      return score > otherStudent.score;//分数按照从大到小进行比较 

        //比较两个学生的成绩是否相同,不相同的话按照分数从大到校排序,否则的话按照名称的Ascii顺序进行排序 
        return score != otherStudent.score ? score > otherStudent.score : 
name < otherStudent.name;
    }
    
    friend ostream& operator<<(ostream &os,const Student &student)
    {
        os << "Student:" << student.name << " " <
    void printArr(T arr[],int n){
        for(int i = 0; i < n; i++)
            cout << arr[i] << " ";
        cout << endl;
        return;
    }   
}

#endif //SELECTIONSORT_SORTTESTHELPER_H

//test driver program
#include    //cin,cout
#include   //swap
#include "student.h"//自定义.h文件
using namespace std;

template   //泛型,是函数更通用
void selectionSort(T a[],int n)
{//寻找[i,n)区间里的最小值 
    int minIndex;
    
    for(int i = 0; i < n-1; i++){
        minIndex = i;
        for(int j = i + 1; j < n; j++){
            if(a[j] < a[minIndex])
                minIndex = j;
        }
        swap(a[i],a[minIndex]); //swap the numbers
    }

}
int main()
{
    //test integer
    int arr[10] = {10,9,8,7,6,5,4,3,2,1}; 
    selectionSort(arr,10);
    student::printArr(arr,10);//print out the elements of the array
    
    //test float
    float b[4] = {4.4,3.3,2.2,1.1};
    selectionSort(b,4);
    student::printArr(b,4);//print out the elements of the array
    
    //test string
    string c[4] = {"D","C","B","A"};
    selectionSort(c,4);
    student::printArr(c,4);//print out the elements of the array
    
    //test self defination
    student::Student d[4] = {{"D",90},{"C",100},{"B",95},{"A",95}};//Reference the structment through student.h 
    selectionSort(d,4); 
    student::printArr(d,4); //Reference to print out
    return 0;
}

You can leave me a message if you find out any mistake in my diary, I'll correct it, thanks.

你可能感兴趣的:(c++ STL---selectionSort improvement)