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

 

 

  

 

 

 

 

 

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM