函数对象:一个重载了运算符()的个对象,可以像一个函数一样使用。
①普通的函数
bool comp(int val)
{
return val > 3;
}
②函数对象,声明为模板类,并可以接受参数,具有更大扩展性
template<typename T>
class Comp
{
public:
Comp(T val) {m_val = val;}
bool operator() (T val) {return val > m_val;}
private:
T m_val;
};
调用上面两种情况,实际是一样,但是函数对象可以设置参数,能够灵活控制比较值大小
vector<int> vec;
for (int i = 1; i< 20; ++i)
vec.push_back(i);
int count = count_if(vec.begin(), vec.end(), comp);
cout<<count<<endl;
count = count_if(vec.begin(), vec.end(), Comp<int>(5));
cout<<count<<endl;
vector<char> c_vec;
for (char c = 'a'; c < 'z'; ++c)
c_vec.push_back(c);
cout<<count_if(c_vec.begin(), c_vec.end(), Comp<char> ('c'))<<endl;
③自己写的统计函数
template<typename T, typename FUNC>
int count_n(T *arr, int n, FUNC func)
{
int count = 0;
for (int i = 0; i < n; ++i)
if (func(arr[i]))
count++;
return count;
}
调用统计函数
int arr[] = {2, 4, 5, 7, 9, 333};
count = count_n<int, Comp<int> >(arr, sizeof(arr) / sizeof(int), Comp<int>(1));
cout<<count<<endl;
④在网上找一个remove_if的例子,觉得很不错
[cpp] view plaincopy
#ifndef STRING_MATCH_HPP_
#define STRING_MATCH_HPP_
#include <string>
#include <functional>
using std::string;
typedef unsigned int UINT;
enum findmodes
{
FM_INVALID = 0,
FM_IS,
FM_STARTSWITH,
FM_ENDSWITH,
FM_CONTAINS
};
typedef struct tagFindStr
{
UINT iMode;
string szMatchStr;
} FindStr;
typedef FindStr* LPFINDSTR;
class FindMatchingString : public std::unary_function<string, bool>
{
public:
FindMatchingString(const LPFINDSTR lpFS) : m_lpFS(lpFS) {}
bool operator()(string& strCmp) const
{
bool retVal = false;
string strMatch = m_lpFS->szMatchStr;
switch(m_lpFS->iMode)
{
case FM_IS:
retVal = (strCmp == strMatch);
break;
case FM_STARTSWITH:
retVal = (strCmp.find(strMatch)==0);
break;
case FM_ENDSWITH:
retVal = (strCmp.find(strMatch)==(strCmp.length()-strMatch.length()));
break;
case FM_CONTAINS:
retVal = (strCmp.find(strMatch) != string::npos);
break;
}
return retVal;
}
private:
LPFINDSTR m_lpFS;
};
#endif /* STRING_MATCH_HPP_ */
接着就是使用remove_if方法了。文件main.cpp
[cpp] view plaincopy
#include <string>
#include <vector>
#include <iostream>
#include <algorithm>
#include "header/string_match.hpp"
using std::vector;
using std::string;
using std::cout;
using std::endl;
//using std::remove_if;
int main(int argc, char* argv[])
{
vector<string> vs;
vs.push_back("Alice");
vs.push_back("Bob");
vs.push_back("Cart");
vs.push_back("Duncan");
vs.push_back("Kelvin");
cout << "Before remove:\n[";
for (vector<string>::iterator iter=vs.begin();iter!=vs.end();iter++)
{
cout << *iter << ", ";
}
cout << "]" << endl;
FindStr fs;
fs.iMode = FM_CONTAINS;
fs.szMatchStr = "Alice";
vs.erase(std::remove_if(vs.begin(), vs.end(), FindMatchingString(&fs)), vs.end());
cout << "After remove:\n[" ;
for (vector<string>::iterator iter=vs.begin();iter!=vs.end();iter++)
{
cout << *iter << ", ";
}
cout << "]" << endl;
return 0;
}