C++在成員函數(shù)中使用STL的find_if函數(shù)實例
本文實例講述了C++在成員函數(shù)中使用STL的find_if函數(shù)的方法。分享給大家供大家參考。具體方法分析如下:
一般來說,STL的find_if函數(shù)功能很強大,可以使用輸入的函數(shù)替代等于操作符執(zhí)行查找功能(這個網(wǎng)上有很多資料,我這里就不多說了)。
比如查找一個數(shù)組中的奇數(shù),可以用如下代碼完成(具體參考這里: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
如果把上述代碼加入到類里面,寫成類的成員函數(shù),又是什么效果呢?
比如如下類代碼:
#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; }
會出現(xiàn)類似下面的錯誤:
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函數(shù)和mem_fun函數(shù)加上this指針搞定的。
完整實例代碼點擊此處本站下載。
希望本文所述對大家的C++程序設計有所幫助。
相關文章
c語言中單引號和雙引號的區(qū)別(順利解決從字符串中提取IP地址的困惑)
c語言中的單引號和雙引號可是有很大區(qū)別的,使用之前一定要了解他們之間到底有什么不同,下面小編就給大家詳細的介紹一下吧,對此還不是很了解的朋友可以過來參考下2013-07-07使用C++實現(xiàn)MySQL數(shù)據(jù)庫連接池
這篇文章主要為大家詳細介紹了如何使用C++實現(xiàn)MySQL數(shù)據(jù)庫連接池,文中的示例代碼講解詳細,具有一定的借鑒價值,有需要的小伙伴可以了解下2024-03-03c++ 形狀類Shape(派生出圓類Circle和矩形類Rectangle)
通過C++方式,建立一個形狀類Shape作為基類,派生出圓類Circle和矩形類Rectangle 求出面積并獲取相關信息2020-11-11深入Main函數(shù)中的參數(shù)argc,argv的使用詳解
本篇文章是對Main函數(shù)中的參數(shù)argc,argv的使用進行了詳細的分析介紹,需要的朋友參考下2013-05-05