c++ STL---selectionSort improvement

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

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

//student.h file

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

#include <iostream>
#include <string>

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 << " " <<student.score << endl;
        return os;
    }
};

    template<typename T>
    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 <iostream>   //cin,cout
#include <algorithm>  //swap
#include "student.h"//自定义.h文件
using namespace std;

template <typename T>  //泛型,是函数更通用
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.

©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • 18.10.17 星期三 晴 今天数学考试了成绩还可以100分,我看了看题不难,只要认真用心做了就没...
    周一成长日记阅读 150评论 0 1
  • 你是否曾经想要学好英语,背了几天单词,念了几篇文章,但是不久就放弃了? 你是否曾经自学编程,短短几天就从入门到放弃...
    明白1阅读 877评论 1 5
  • 快乐读书30分钟
    玉梅_9dc8阅读 116评论 0 0
  • 11月3日。 早上睁开眼睛,欧卡脑海里第一个念头就是,自己三周岁了。 欧卡,这只一向自诩没耐心、有勇气、热血沸腾的...
    绿萝吖阅读 286评论 0 1
  • 君子之交淡如水,小人之交甘若醴。 每次急用钱,总有几个知己雪中送炭,这就够了。 感谢每个在关键时候伸出援手的朋友,...
    凤之子阅读 270评论 0 2