复习C++ 友元函数 和 运算符重载 模板函数
1、C++模板函数
模板是泛型的基础
1、函数模板
定义形式
template <class type>
ret-type func-name(parameter list)
{
// 函数的主体
}
示例:
template<typename T>
T Max(T a, T b) {
return a > b ? a : b;
}
2、类模板
template <class T>
class Stack {
private:
vector<T> elems;
public:
void push(T const& elem);
T const & top();
void pop();
};
2、运算符重载
重载的运算符是带有特殊名称的函数,函数名是由关键字 operator 和其后要重载的运算符符号构成的。
struct Student {
char *name;
int score;
//意思是当前student结构体与另一个student结构体做大于号比较
bool operator >(const Student &otherStudent) {
return score != otherStudent.score ? score > otherStudent.score
: &name > &otherStudent.name;
}
};
结合 1 和 2
Student student1 = {"aa", 80};
Student student2 = {"bb", 81};
Student student = Max(student1, student2);
3、利用模板和运算符重载 写一个选择排序的算法
template <typename T>
void selectionSort(T arr[],int n){
for (int i = 0; i < n; ++i) {
int minIndex = i;
for (int j = i+1; j < n ; ++j) {
if (arr[j] < arr[minIndex] ){
swap(arr[j],arr[minIndex]);
}
}
}
}
结构体Student
#ifndef ALGORITHMDEMO_STUDENT_H
#define ALGORITHMDEMO_STUDENT_H
#include <android/log.h>
#define TAG "dsh"
#define LOGD(...)__android_log_print(ANDROID_LOG_DEBUG,TAG,__VA_ARGS__)
struct Student {
char *name;
int score;
bool operator >(const Student &otherStudent) {
return score != otherStudent.score ? score > otherStudent.score
: &name > &otherStudent.name;
}
bool operator <(const Student &otherStudent) {
return score != otherStudent.score ? score < otherStudent.score
: &name < &otherStudent.name;
}
};
#endif
测试程序:
int arr[10] = {10,9,8,7,6,5,4,3,2,1};
selectionSort(arr,10);
for (int i = 0; i < 10; ++i) {
LOGD("最大数是 %d", arr[i]);
}
Student arr1[3] = {{"aa", 89},{"bb", 81},{"bb", 84}};
selectionSort(arr1,3);
for (int i = 0; i < 3; ++i) {
LOGD("最大数是 %d", arr1[i].score);
}