c++辅助函数:
常用辅助函数 max() 、min()
//std详解如下
//两个参数
template <class T>
inline const T& min(const T& a,const T& b) {
return b < a ? b : a;
}
template <class T>
inline const T& max(const T&a,const T& a) {
return a <b ? b : a;
}
//三个参数 第三个参数为评判标准
template <class T, class Compare>
inline const T& min(const T& a,const T& b,Compare comp) {
return comp(b,a) ? b : a;
}
template <class T, class Compare>
inline const T& max(const T& a,const T& b,Compare comp) {
return comp(a,b) ? b : a;
}
实例
#include <iostream>
#include <algorithm>
using namespace std;
bool int_ptr_less(int *a,int *b)
{
return *a < *b;
}
int main()
{
int x =50;
int y =100;
int *px =&x;
int *py =&y;
int *pmax;
int *pmin;
pmax =max(px,py,int_ptr_less);
pmin =min(px,py,int_ptr_less);
cout << "max =" <<*pmax << endl;
cout << "min = " << *pmin << endl;
return 0;
}
常用辅助函数 swap()
template<class T>
inline void swap(T& a, T& b) {
T tmp(a);
a =b;
b =tmp;
}
//例子
using namespace std;
class MyContainer {
private :
int *elems;
int num;
public:
void swap(MyContainer &x)
{
std::swap(elems,x.elems);
std::swap(num,x.num);
}
void Init(MyContainer &x,int a[],int n)
{
x.elems =a;
x.num =n;
}
void print()
{
cout << "num :" ;
cout << num <<endl;
cout << "elems: ";
for (int i =0; i <num; i++)
cout << elems[i] << " ";
cout <<endl;
}
};
inline void swap(MyContainer &c1,MyContainer &c2)
{
c1.swap(c2);
}
int main()
{
MyContainer c1,c2;
int a[] ={1,2,3};
int b[] ={4,5,6,7};
c1.Init(c1,a,3);
c2.Init(c2,b,4);
cout << "swap前:" <<endl;
cout <<"C1:" <<endl;
c1.print();
cout << "C2: " <<endl;
c2.print();
swap(c1,c2);
cout << "交换后:"<<endl;
cout <<"C1:" <<endl;
c1.print();
cout << "C2: " <<endl;
c2.print();
return 0;
}