《我的第一本c++书》学习笔记:STL之函数的相关内容(二)
2013-08-07 17:33
441 查看
函数指针应用在STL算法中:
这里如果是普通函数则用ptr_fun(),如果是成员函数则调用mem_fun_ref()。
以下则为调用成员函数来实现:
代码如下:
// 3.cpp : 定义控制台应用程序的入口点。 // #include "stdafx.h" #include <iostream> #include <vector> #include <algorithm> #include <functional> using namespace std; class Student { public: Student() { m_strName = ""; m_nHeight = 0; } public: Student( string strName, int nHeight ) : m_strName(strName), m_nHeight(nHeight) { } int GetHeight() { return m_nHeight; } string GetName() { return m_strName; } private: string m_strName; int m_nHeight; }; bool countHeight( int nHeight, Student st) { return st.GetHeight() > nHeight; } int _tmain(int argc, _TCHAR* argv[]) { vector<Student> vecStu; Student st1( "zhouzhou", 180 ); Student st2( "xiaoxiao", 162 ); Student st3( "huhu", 176 ); vecStu.push_back(st1); vecStu.push_back(st2); vecStu.push_back(st3); int nStandardHeight = 160; int nCount = count_if(vecStu.begin(), vecStu.end(), bind1st(ptr_fun(countHeight), nStandardHeight)); cout<<"身高大于"<<nStandardHeight<<"人数为:"<<nCount<<endl; return 0; }
这里如果是普通函数则用ptr_fun(),如果是成员函数则调用mem_fun_ref()。
以下则为调用成员函数来实现:
代码如下:
// 3.cpp : 定义控制台应用程序的入口点。 // #include "stdafx.h" #include <iostream> #include <vector> #include <algorithm> #include <functional> using namespace std; class Student { public: Student() { m_strName = ""; m_nHeight = 0; } public: Student( string strName, int nHeight ) : m_strName(strName), m_nHeight(nHeight) { } int GetHeight() { return m_nHeight; } string GetName() { return m_strName; } bool countHeight( int nHeight) { return m_nHeight > nHeight; } private: string m_strName; int m_nHeight; }; int _tmain(int argc, _TCHAR* argv[]) { vector<Student> vecStu; Student st1( "zhouzhou", 180 ); Student st2( "xiaoxiao", 162 ); Student st3( "huhu", 176 ); vecStu.push_back(st1); vecStu.push_back(st2); vecStu.push_back(st3); int nStandardHeight = 160; int nCount = count_if(vecStu.begin(), vecStu.end(), bind2nd(mem_fun_ref(&Student::countHeight), nStandardHeight)); cout<<"身高大于"<<nStandardHeight<<"人数为:"<<nCount<<endl; return 0; }
相关文章推荐
- 《我的第一本c++书》学习笔记:STL之函数的相关内容(一)
- 《我的第一本c++书》学习笔记:STL之函数模板和类模板
- 《我的第一本c++书》学习笔记:STL中函数对象
- 《我的第一本c++书》学习笔记:STL之vector容器的常用操作函数
- 《我的第一本c++书》学习笔记:STL中的一些通用算法(一)
- STL中流相关的输入输出符和get函数彻底总结:cin、cin.get()、cin.getline()、getline()、gets()等函数的用法
- 虚函数相关内容总结
- linux下printf函数为什么不加\n就不能输出相关的内容 ?
- 侯捷STL学习(12)--STL相关内容hash+tuple
- STL之--输入输出流状态的相关函数操作
- 《我的第一本c++书》学习笔记:STL之Lambda表达式
- 《我的第一本c++书》学习笔记:STL之shared_ptr(上)
- 基于Windows的设备管理开发(主要阐述SetupDi系列函数及其相关内容)
- [arm驱动]注册函数相关内容 推荐
- 《STL源码剖析》学习笔记1——stl_config.h中和编译器相关的一些宏定义的解释
- sprintf()函数格式内容及相关操作
- STL中vector容器begin(),end(),push_back()等相关函数
- CDays-2 习题一 (改进函数)及相关内容解析。Python 基础教程
- STL与泛型编程<九>:迭代器相关辅助函数
- STL中与二分查找相关的4个函数