c++中巧用函數對象傳遞附加資訊

來源:互聯網
上載者:User

定義了叫用作業符的類,其對象常稱為函數對象,即它們是行為類似函數的對象。可以為類類型的對象重載函數叫用作業符。一般為表示操作的類重載叫用作業符。函數叫用作業符必須聲明為成員函數。一個類可以定義函數叫用作業符的多個版本,由形參的數目或類型加以區別。

例如,可以定義名為 absInt 的結構,該結構封裝將 int 類型的值轉換為絕對值的操作:

class absInt{public:    int operator() (int val)     {         return val < 0 ? -val : val;     }};

貌似什麼的例子沒什麼吸引力, 下面來個例子.

比如我們有個儲存字串的vector<string> words; 我們想計算其中字元數大於6的個數, 我們現在使用標準庫的函數count_if來計算. count_if最後傳入處理函數,函數形式like this:

 bool funcName(const string &s) ;

此函數只接受一個參數,並且是count_if來為你傳入, 好,下面我們寫個比較函數:

 // determine whether a length of a given word is 6 or more  bool GT6(const string &s)  {      return s.size() >= 6;  }

這樣來調用就ok了

vector<string>::size_type wc = count_if(words.begin(), words.end(), GT6); 

很明顯這樣有一個最大的缺點就是,6是寫入程式碼, 如果我要大於7的個數呢? 在寫一個? 那大於8的呢?..............

有的傢伙說: 日, 把6定義成一個變數就好了. 那是可以,但是太不優雅了(裝一次逼). 況且如果需要的不是這種簡單的大於6個數的需求呢?

有的傢伙說: 靠你媳婦不戴套, 直接寫比這簡單啊!  我太陽,也是哈, 但是如果是一個比較複雜的演算法,別人就提供了這樣的介面呢?

......

好了,那就函數對象唄, 不然不跑題了, 日.

 // determine whether a length of a given word is longer than a stored bound class GT_cls { public:     GT_cls(size_t val = 0): bound(val) { }     bool operator()(const string &s){ return s.size() >= bound; } private:     std::string::size_type bound; }; 

調用方式:

//大於6個cout << count_if(words.begin(), words.end(), GT_cls(6)) << " words 6 characters or longer" << endl;//大於5個cout << count_if(words.begin(), words.end(), GT_cls(5)) << " words 5 characters or longer" << endl;//迴圈體for (size_t i = 0; i != 11; ++i)     cout << count_if(words.begin(), words.end(), GT(i))<< " words " << i << " characters or longer" << endl; 

 

 

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.