算法与数据结构 学习笔记2

继上一小结 修改测试用例

这个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;

}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

东东要拼命

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值