C++的一些辅助函数:min(),max(),swap()等

1.比较两数的较大者和较小者:max(),min()

  max()和min()定义于<algorithm>,如下:

  

 1 namespace std{
 2     template <class T>
 3     inline const T& min(const T& a,const T& b) {
 4         return b < a ? b : a;
 5     }         
 6     template <class T>
 7     inline const T& max(const T&a,const T& a) {
 8         return a <b ? b : a;
 9     }
10 }    

上面两个函数的另一版本,接受一个额外的参数作为比较准则:

namespace std{
  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;
  }

}

实例1:

#include <iostream>
#include <algorithm>
using namespace std;

int main()
{
  int x =50;
  int y =100;
  cout <<"min = " <<min<int>(x,y)<<endl;
  cout <<"max = " <<max<int>(x,y) <<endl;
  return 0;
}

//输出:

min = 50
max = 100

实例2

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

//输出:

max =100
min = 50
注意:max()和min()都要求它们所接受的两个参数的类别必须一样。否则:

int i,

float f;

max(i,f);//ERROR:argument types don't match;

2.两值交换:swap()

  定义于<algorithm>:

  

namespace std  {
   template<class T>
  inline void swap(T& a, T& b) {
        T tmp(a);
        a =b;
        b =tmp;
    }      
}

利用swap(),通过模板特化或函数重载,我们可以为更复杂的型别提供特殊的交换,我们可以直接交换对象内部成员,不必劳师动众地反复赋值,这将大大地节约时间:

实例:

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

//输出:

swap前:
C1:
num :3
elems: 1 2 3
C2:
num :4
elems: 4 5 6 7
交换后:
C1:
num :4
elems: 4 5 6 7
C2:
num :3
elems: 1 2 3

 

 

  

 

 

 

 

 

 

posted on 2014-04-16 13:00  敖天  阅读(23769)  评论(0编辑  收藏  举报

导航