C++编程思想 第2卷 第6章 通用算法 函数对象 自动创建函数对象

标准函数对象greater是一个二元函数对象
当它的第1个参数大于第2个参数时返回true
不能通过一个算法如remove_copy_if()直接把它应用到整数序列

//: C06:CopyInts4.cpp
// From "Thinking in C++, Volume 2", by Bruce Eckel & Chuck Allison.
// (c) 1995-2004 MindView, Inc. All Rights Reserved.
// See source code use permissions stated in the file 'License.txt',
// distributed with the code package available at www.MindView.net.
// Uses a standard function object and adaptor.
#include <algorithm>
#include <cstddef>
#include <functional>
#include <iostream>
#include <iterator>
using namespace std;

int main() {
  int a[] = { 10, 20, 30 };
  const size_t SIZE = sizeof a / sizeof a[0];
  remove_copy_if(a, a + SIZE,
                 ostream_iterator<int>(cout, "\n"),
                 bind2nd(greater<int>(), 15));
  getchar();
} ///:~


输出
10
这个程序没用用户自己定义的判定函数gt15()
函数对象适配器bind2nd()是一个模板函数
它创建一个binder2nd类型的函数对象


计算某个序列中不等于20的元素的个数
程序中有一个标准二元函数对象equal_to
还有一个函数对象适配器not1()
该函数对象适配器以一元函数对象作为参数并转化其实际值

//: C06:CountNotEqual.cpp
// From "Thinking in C++, Volume 2", by Bruce Eckel & Chuck Allison.
// (c) 1995-2004 MindView, Inc. All Rights Reserved.
// See source code use permissions stated in the file 'License.txt',
// distributed with the code package available at www.MindView.net.
// Count elements not equal to 20.
#include <algorithm>
#include <cstddef>
#include <functional>
#include <iostream>
using namespace std;

int main() {
  int a[] = { 10, 20, 30 };
  const size_t SIZE = sizeof a / sizeof a[0];
  cout << count_if(a, a + SIZE,
                   not1(bind1st(equal_to<int>(), 20)));// 2
  getchar();
} ///:~


输出
2

count_if()调用位于它的第3个参数位置的函数对序列中的每一个元素进行判定
并且在每次返回true时使其内部计数器增1

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值