C++ 模板化的student类对象的直接插入排序, >、<、<<运算符重载,模板,两种模板化的交换数据函数
1、student类对象
(1)基本成员变量和成员函数定义:
class student{
private:
string name;
double score;
int *index;
public:
student() :index(NULL){}
student(string s, double n, int *x) :name(s), score(n), index(x){}
~student(){}
};
(2)student类中>、<、<<运算符重载
bool operator <(const student & others){//重载运算符"<": 按成绩升序(成绩相同时,按名字升序)
//return score < others.score; //只按成绩升序排序。
return score == others.score ? name < others.name : score < others.score;
}
bool operator >(const student & others){//重载运算符">": 按成绩降序(成绩相同时,按名字降序)
return score == others.score ? name > others.name : score > others.score;
}
friend ostream& operator<<(ostream &os, const student &stu){//重载输出运算符“<<”
os << stu.name << "\t" << stu.score << "\t" << *stu.index << "\t";
return os;
}
2、直接插入排序(模板)
//插入排序--引用交换--升序
template<class T>
void insertSort(vector<T> &a){
for (int i = 1; i < a.size(); i++){
for (int j = i; j > 0; j--){
if (a[j] < a[j - 1])myswap2(a[j], a[j - 1]);//当T为一个类时,需要对 运算符“<” 进行重载(以满足 比较的需要:a[j] < a[j - 1]),无需将类也整成模板。
}
}
}
//插入排序--指针交换--降序
template<class T>
void insertSort2(vector<T> &a){
for (int i = 1; i < a.size(); i++){
for (int j = i; j > 0; j--){
if (a[j] > a[j - 1])myswap3(&a[j], &a[j - 1]);//当T为一个类时,需要对 运算符“>” 进行重载(以满足 比较的需要:a[j] < a[j - 1]),无需将类也整成模板。
}
}
}
3、两种交换数据的函数(模板)
//不仅使用与简单的同种数据类型(如int\float\double\char)之间的数据交换,还适用于类对象之间的交换数据
//引用+第三者 中间转换变量
template<class T>
void myswap2(T &a, T &b){
T t;
t = a, a = b, b = t;
}
//不仅使用与简单的同种数据类型(如int\float\double\char)之间的数据交换,还适用于类对象之间的交换数据
//指针+第三者 中间转换变量
template<class T>
void myswap3(T *a, T *b){
T t;
t = *a, *a = *b, *b = t;
}
4、vector的输出(模板)
//输出类对象的vector
//只需要 在类中重载输出运算符"<<"
template<class T>
void disp(const vector<T> &v){
for (auto c : v){
cout << c;
}
cout << endl;
}
5、测试代码
void test(){
string s[] = { "Charles", "Athene", "Nick", "Leona" };
double score[] = { 85, 98, 79, 85 };
int index[] = { 0, 1, 2, 4 };
int n = sizeof(score) / sizeof(score[0]);
//学生信息录入
vector<student> v;
for (int i = 0; i < n; ++i){
student tmp(s[i], score[i], &index[i]);
v.push_back(tmp);
}
disp(v);//显示学生信息
cout << "------------insertSort------------" << endl;
insertSort(v);//对 学生对象向量v 按成绩升序排序(成绩相同时,按名字升序)。
disp(v);
insertSort2(v);//对 学生对象向量v 按成绩降序排序(成绩相同时,按名字降序)。
disp(v);
}
int main(){
test();
return 0;
}