C++在成員函數(shù)中使用STL的find_if函數(shù)實(shí)例
本文實(shí)例講述了C++在成員函數(shù)中使用STL的find_if函數(shù)的方法。分享給大家供大家參考。具體方法分析如下:
一般來說,STL的find_if函數(shù)功能很強(qiáng)大,可以使用輸入的函數(shù)替代等于操作符執(zhí)行查找功能(這個(gè)網(wǎng)上有很多資料,我這里就不多說了)。
比如查找一個(gè)數(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)類似下面的錯(cuò)誤:
error C3867: 'CTest::IsOdd': function call missing argument list; use '&CTest::IsOdd' to create a pointer to member
今天我就遇到了這個(gè)問題,這里把解決方案貼出來,僅供參考:
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è)計(jì)有所幫助。
上一篇:C++ COM編程之什么是組件?
欄 目:C語言
本文標(biāo)題:C++在成員函數(shù)中使用STL的find_if函數(shù)實(shí)例
本文地址:http://www.jygsgssxh.com/a1/Cyuyan/3316.html
您可能感興趣的文章
- 04-02func函數(shù)+在C語言 func函數(shù)在c語言中
- 04-02c語言沒有round函數(shù) round c語言
- 04-02C語言中怎么打出三角函數(shù) c語言中怎么打出三角函數(shù)的值
- 01-10深入理解C++中常見的關(guān)鍵字含義
- 01-10使用C++實(shí)現(xiàn)全排列算法的方法詳解
- 01-10APUE筆記之:進(jìn)程環(huán)境詳解
- 01-10c++中inline的用法分析
- 01-10用C++實(shí)現(xiàn)DBSCAN聚類算法
- 01-10全排列算法的非遞歸實(shí)現(xiàn)與遞歸實(shí)現(xiàn)的方法(C++)
- 01-10C++大數(shù)模板(推薦)


閱讀排行
本欄相關(guān)
- 04-02c語言函數(shù)調(diào)用后清空內(nèi)存 c語言調(diào)用
- 04-02func函數(shù)+在C語言 func函數(shù)在c語言中
- 04-02c語言的正則匹配函數(shù) c語言正則表達(dá)
- 04-02c語言用函數(shù)寫分段 用c語言表示分段
- 04-02c語言中對數(shù)函數(shù)的表達(dá)式 c語言中對
- 04-02c語言編寫函數(shù)冒泡排序 c語言冒泡排
- 04-02c語言沒有round函數(shù) round c語言
- 04-02c語言分段函數(shù)怎么求 用c語言求分段
- 04-02C語言中怎么打出三角函數(shù) c語言中怎
- 04-02c語言調(diào)用函數(shù)求fibo C語言調(diào)用函數(shù)求
隨機(jī)閱讀
- 08-05織夢dedecms什么時(shí)候用欄目交叉功能?
- 01-10使用C語言求解撲克牌的順子及n個(gè)骰子
- 01-10C#中split用法實(shí)例總結(jié)
- 01-11ajax實(shí)現(xiàn)頁面的局部加載
- 08-05DEDE織夢data目錄下的sessions文件夾有什
- 08-05dedecms(織夢)副欄目數(shù)量限制代碼修改
- 01-10delphi制作wav文件的方法
- 04-02jquery與jsp,用jquery
- 01-11Mac OSX 打開原生自帶讀寫NTFS功能(圖文
- 01-10SublimeText編譯C開發(fā)環(huán)境設(shè)置


