本文主要是学习C++标准库中的排序算法的应用,一般来讲C++提供的排序算法只能针对int类型的数据进行相应升序或降序。本文中用的是ID类类型的数据,拥有两个参量,一个是string类型的name,另一个是int类型的score数据,所以如果对它们进行排序的话需要对==和<运算符进行运算符重载,这也是C++一大亮点之一,使得程序开发变得更加灵活!引用《The C++ Programming Language》中的运算符重载说明:
1. 可以供用户自己去定义运算符的有:
用户不可以进行定义的有:
::(作用域解析符)
.(成员选择运算符)
.*(通过到成员的指针做成员选择运算符)
?:(三元运算符)
typeid、sizeof(都不可以用户自定义)
它们都以名字作为其第二个参数,而且提供的是引用成员的最基本语义。
在没有重载==和<的时候运行程序会报错,如下所示:
加了对==和<运算符重载过后就可以正确的对包含字符型和整型的ID类型的参数进行排序,只需调用sort(AA,BB)函数即可进行升序排列,标准模板库中同时也可以进行降序排列,只需添加一个如下代码即可:
bool compare(const ID& x,const ID& y)
{
return x.score>y.score;
}
然后调用sort(ids.begin(),ids.end(),compare);
此时就会有以下结果:
升序结果如下图所示:
Code:
/*
*作者:att0206
*上海师范大学
*2017/03/18
*/
#include<iostream>
#include<string>
#include<vector>
#include<algorithm>
using namespace std;
void showText()
{
cout<<"**********************************"<<endl;
cout<<"**** Welcoming! ****"<<endl;
cout<<"**********************************"<<endl;
}
class ID{
public:
ID():name(""),score(0){}
ID(string n,int s):name(n),score(s){}
string name;
int score;
};
//重载运算符
bool operator==(const ID& x,const ID& y) //重载==运算符
{
return (x.name == y.name)&&(x.score == y.score);
}
bool operator<(const ID& x,const ID& y)
{
return x.score<y.score;
}
int main(int argc,char** argv)
{
showText();
vector<ID> ids;
vector<ID>::iterator iter;
ids.push_back(ID("Wang",8)); //使用了拷贝构造函数
//cout<<&ID::show<<endl;
ids.push_back(ID("Chao",5));
ids.push_back(ID("Long",3));
ids.push_back(ID("SHNU",9));
for(iter = ids.begin();iter != ids.end();++iter) //对ids进行遍历
{
cout<< (*iter).name<<" "<<(*iter).score<<endl;
}
sort(ids.begin(),ids.end()); //调用排序算法
cout<<"The sort output :"<<endl;
for(iter = ids.begin();iter != ids.end();++iter)
{
cout<< (*iter).name<<" "<<(*iter).score<<endl;
}
for(;;);
return 0;
}
以上代码是针对升序的,如果想实现降序功能,自行修改添加相关代码。
对于C++中提供的丰富STL标准库的接口很是方便,只需要知道如何进行调用相关的API很快就可以解决问题。对于算法的学习,只是以排序作为一个简单的例子,后面还会具体的学习算法。