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;
}