国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁 > 編程 > C++ > 正文

C++在成員函數(shù)中使用STL的find_if函數(shù)實(shí)例

2020-01-26 15:16:28
字體:
供稿:網(wǎng)友

本文實(shí)例講述了C++在成員函數(shù)中使用STL的find_if函數(shù)的方法。分享給大家供大家參考。具體方法分析如下:

一般來說,STL的find_if函數(shù)功能很強(qiáng)大,可以使用輸入的函數(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;}

運(yùn)行結(jié)果:

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

完整實(shí)例代碼點(diǎn)擊此處本站下載

希望本文所述對大家的C++程序設(shè)計有所幫助。

發(fā)表評論 共有條評論
用戶名: 密碼:
驗(yàn)證碼: 匿名發(fā)表
主站蜘蛛池模板: 澄迈县| 双辽市| 北宁市| 石首市| 山阳县| 随州市| 巧家县| 瑞昌市| 洛阳市| 兴山县| 景宁| 化德县| 通辽市| 德州市| 吉安市| 龙游县| 霍山县| 康平县| 房产| 武胜县| 宁都县| 麟游县| 惠安县| 聂荣县| 房山区| 胶州市| 沐川县| 昌黎县| 乐安县| 建湖县| 淄博市| 龙泉市| 广灵县| 柳林县| 横山县| 顺昌县| 札达县| 万安县| 湖南省| 中西区| 江阴市|