我要开始学习C++了,今天把C里的冒泡法用C++实现了一下
#include <string>
using namespace std;
//运动员类,姓名,学号,成绩(头文件)
class Athlete{
public:
Athlete(string,int,float);
string getname();
int getid();
float getscore();
private:
string name;
int id ;
float score;
};
#include "athlete.h"
#include <string>
using namespace std;
Athlete::Athlete(string n,int i,float s){
name=n;
id=i;
score=s;
}
string Athlete::getname(){
return name;
}
int Athlete::getid(){
return id;
}
float Athlete::getscore(){
return score;
}
// 冒泡法测试 对象排序 程序入口
#include "athlete.h"
#include <string>
#include <iostream>
using namespace std;
int main(){
//建立一组对象用于排序
Athlete ath[8]={
Athlete("yubin",27,25.8),
Athlete("zhangrui",34,34.56),
Athlete("liuhai",37,21.24),
Athlete("liema",25,67.34),
Athlete("helin",38,45.67),
Athlete("quchao",29,76.89),
Athlete("lidian",36,87.75),
Athlete("wanghai",14,53.27),
};
// cout<<"the name is "<<ath[4].getname()<<endl;
// cout<<"the score is "<<ath[2].getscore()<<endl;
//按对象组的成绩从大到小排列
//外层循环
for(int i=0;i<8;i++){
//里层循环
for(int j=i;j<8;j++){
Athlete temp("default",0,0);
//如果前面的成绩小于后者 则和后者调换
if(ath[i].getscore()<ath[j].getscore()){
temp=ath[i];
ath[i]=ath[j];
ath[j]=temp;
}
}
}
//输出排序后的名单
for(i=0;i<8;i++){
cout<<"name :"<<ath[i].getname()<<" id :"<<ath[i].getid()<<" score:"<<ath[i].getscore()<<endl;
}
return 0;
}