BLUEWIKI 发表于 2019-7-11 18:44

BOOST 练习程序(1)

接触BOOST没多久,这是自己目前能想到的解。(可能有更好的解答,还望不吝赐教)
题目:
简化以下程序,将函数对象 divide_by 转换为一个函数,并将 for 循环替换为用一个标准的 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;
}

自己给出的解答:
#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);
}
页: [1]
查看完整版本: BOOST 练习程序(1)