您的位置:首页 > 编程语言 > C语言/C++

《我的第一本c++书》学习笔记:STL之函数的相关内容(二)

2013-08-07 17:33 441 查看
函数指针应用在STL算法中:

// 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;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: