对于一整数vector,我们必须返回新的vector, 采取小于或大于等不同条件下返回不同的vector。
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
typedef bool (*func_type)(int, int);
bool less_than(int a, int b)
{
return a < b ? true : false;
}
bool more_than(int a, int b)
{
return a > b ? true : false;
}
//vector<int> filter(vector<int> vec, int value, bool (*pred)(int, int))
vector<int> filter(vector<int> vec, int value, func_type pred)
{
vector<int> nvec;
for (size_t i = 0; i < vec.size(); ++i)
{
if (pred(vec[i], value))
{
nvec.push_back(vec[i]);
}
}
return nvec;
}
void print_ivec(vector<int> ivec, const string str)
{
cout << str << ": ";
vector<int>::const_iterator it = ivec.begin();
for (; it != ivec.end(); ++it)
{
cout << *it << ' ';
}
cout << endl;
}
int main(int argc, const char *argv[])
{
vector<int> ivec;
for (int i = 0; i < 20; ++i)
{
ivec.push_back(i);
}
print_ivec(ivec, "init_ivec");
vector<int> nvec;
nvec = filter(ivec, 10, less_than);
print_ivec(nvec, "less_than");
nvec = filter(ivec, 10, more_than);
print_ivec(nvec, "more_than");
return 0;
}