在成員函數中使用STL的find_if函數


STLfind_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

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

比如如下類代碼:

View Code
#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指針搞定的。

完整代碼參考這里:https://gist.github.com/3910390

好,就這些了,希望對你有幫助。


免責聲明!

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



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