吾爱破解 - LCG - LSG |安卓破解|病毒分析|www.52pojie.cn

 找回密码
 注册[Register]

QQ登录

只需一步,快速开始

查看: 1718|回复: 0
收起左侧

[C&C++ 转载] BOOST 练习程序(1)

[复制链接]
BLUEWIKI 发表于 2019-7-11 18:44
接触BOOST没多久,这是自己目前能想到的解。(可能有更好的解答,还望不吝赐教)
题目:
简化以下程序,将函数对象 divide_by 转换为一个函数,并将 for 循环替换为用一个标准的 C++ 算法来输出数据:
[C++] 纯文本查看 复制代码
#include <algorithm> 
#include <functional> 
#include <vector> 
#include <iostream> 

class divide_by 
  : public std::binary_function<int, int, int> 
{ 
public: 
  int operator()(int n, int div) const 
  { 
    return n / div; 
  } 
}; 

int main() 
{ 
  std::vector<int> numbers; 
  numbers.push_back(10); 
  numbers.push_back(20); 
  numbers.push_back(30); 

  std::transform(numbers.begin(), numbers.end(), numbers.begin(), std::bind2nd(divide_by(), 2)); 

  for (std::vector<int>::iterator it = numbers.begin(); it != numbers.end(); ++it) 
    std::cout << *it << std::endl; 
} 


自己给出的解答:
[C++] 纯文本查看 复制代码
#include <algorithm> 
#include <functional> 
#include <vector> 
#include <iostream>
#include <boost/function.hpp>

int divide_by(int n, int div)
{
	return n / div;
}

void print_1(int num)
{
	printf("==%d==\n", num);
}

int main() 
{
	std::vector<int> numbers; 
	numbers.push_back(10); 
	numbers.push_back(20); 
	numbers.push_back(30); 

	boost::function<int (int, int)> func_1 = divide_by;

	std::transform(numbers.begin(), numbers.end(), numbers.begin(), std::bind2nd(func_1, 2)); 

	std::for_each(numbers.begin(), numbers.end(), print_1);
} 

发帖前要善用论坛搜索功能,那里可能会有你要找的答案或者已经有人发布过相同内容了,请勿重复发帖。

您需要登录后才可以回帖 登录 | 注册[Register]

本版积分规则 警告:本版块禁止灌水或回复与主题无关内容,违者重罚!

快速回复 收藏帖子 返回列表 搜索

RSS订阅|小黑屋|处罚记录|联系我们|吾爱破解 - LCG - LSG ( 京ICP备16042023号 | 京公网安备 11010502030087号 )

GMT+8, 2024-4-29 23:29

Powered by Discuz!

Copyright © 2001-2020, Tencent Cloud.

快速回复 返回顶部 返回列表