读书人

标准库函数对象应用有关问题

发布时间: 2013-04-09 16:45:09 作者: rapoo

标准库函数对象应用问题
本帖最后由 ben302010 于 2013-04-05 16:37:27 编辑

#include <functional>
using std::plus; using std::negate;

#include <iostream>
using std::cout; using std::endl;

#include <vector>
#include <algorithm>
using std::count_if; using std::bind2nd; using std::not1; using std::ptr_fun;
using std::less_equal; using std::vector;

#include <iostream>
using std::cin;

#include <string>
using std::string;

bool size_compare(string s, string::size_type sz)
{
return s.size() >= sz;
}

int main() {

cout << plus<int>()(3,4) << endl; // prints 7

plus<int> intAdd; // function object that can add two int values
negate<int> intNegate; // function object that can negate an int value

// uses intAdd::operator(int, int) to add 10 and 20
int sum = intAdd(10, 20); // sum = 30

cout << sum << endl;

// uses intNegate::operator(int) to generate -10 as second parameter
// to intAdd::operator(int, int)
sum = intAdd(10, intNegate(10)); // sum = 0

cout << sum << endl;

int arry[] = {0,1,2,3,4,5,16,17,18,19};

vector<int> vec(arry, arry + 10);
//我输出大于1小于10的数
cout <<
count_if(vec.begin(), vec.end(),
std::logical_and<int>(bind2nd(std::greater_equal<int>(), 1),
bind2nd(less_equal<int>(), 10)));//这一行报错了,为什么
cout << endl;

cout <<
count_if(vec.begin(), vec.end(),
not1(bind2nd(less_equal<int>(), 10)));
cout << endl;

return 0;
}

logical_and应该怎样使用 标准库函数对象 logical_and
[解决办法]

count_if(vec.begin(), vec.end(),
std::logical_and<int>(bind2nd(std::greater_equal<int>(), 1),
bind2nd(less_equal<int>(), 10)));//这一行报错了,为什么
cout << endl;

因为 logical_and 没有吃两个参数的构造函数。c++03 的 bind* 设计是不完整的,因为缺少一些强有力的模板技术,特别是因为没有 variadic template。楼主要是想学这些技术,建议直接学 c++11 的,旧版的 bind* 全系列已经 deprecated 了。用 c++11,可以这样写。



using namespace std::placeholders;
count_if(vec.begin(), vec.end(),
std::bind(std::logical_and<int>(),
std::bind(std::greater_equal<int>(),_1,1),
std::bind(less_equal<int>(),_1,10)));

不过说是在 lambda 在这里更合适,也简洁直观。

count_if(vec.begin(),vec.end(),[](int const x){return 1<=x && x<=10;});

读书人网 >C++

热点推荐