C++在成員函數中使用STL的find_if函數執行個體_C 語言

來源:互聯網
上載者:User

本文執行個體講述了C++在成員函數中使用STL的find_if函數的方法。分享給大家供大家參考。具體方法分析如下:

一般來說,STL的find_if函數功能很強大,可以使用輸入的函數替代等於操作符執行尋找功能(這個網上有很多資料,我這裡就不多說了)。

比如尋找一個數組中的奇數,可以用如下程式碼完成(具體參考這裡:http://www.cplusplus.com/reference/algorithm/find_if/):

#include <iostream>#include <algorithm>#include <vector>using namespace std;bool IsOdd (int i) { return ((i%2)==1);}int main () { vector<int> myvector; vector<int>::iterator it; myvector.push_back(10); myvector.push_back(25); myvector.push_back(40); myvector.push_back(55); it = find_if (myvector.begin(), myvector.end(), IsOdd); cout << "The first odd value is " << *it << endl; return 0;}

運行結果:

The first odd value is 25

如果把上述代碼加入到類裡面,寫成類的成員函數,又是什麼效果呢?

比如如下類代碼:

#include <iostream>#include <algorithm>#include <vector>using namespace std;class CTest{public: bool IsOdd (int i) {  return ((i%2)==1); } int test () {  vector<int> myvector;  vector<int>::iterator it;  myvector.push_back(10);  myvector.push_back(25);  myvector.push_back(40);  myvector.push_back(55);  it = find_if (myvector.begin(), myvector.end(), IsOdd);  cout << "The first odd value is " << *it << endl;  return 0; }};int main(){ CTest t1; t1.test(); return 0;}

會出現類似下面的錯誤:

error C3867: 'CTest::IsOdd': function call missing argument list; use '&CTest::IsOdd' to create a pointer to member

今天我就遇到了這個問題,這裡把解決方案貼出來,僅供參考:

it = find_if (myvector.begin(), myvector.end(), IsOdd);

改為:

it = find_if(myvector.begin(), myvector.end(),std::bind1st(std::mem_fun(&CTest::IsOdd),this));

用bind1st函數和mem_fun函數加上this指標搞定的。

完整執行個體代碼點擊此處本站下載。

希望本文所述對大家的C++程式設計有所協助。

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.