c++ - 传入一个递增 boost::fusion:vector 元素的函数

标签 c++ boost

我找到了以下代码,我将其用作基础。它描述了如何使用值 6 填充 boost::fusion::vector:

#include <boost/fusion/algorithm.hpp>
#include <boost/fusion/container.hpp>

struct F {
    F(int blah): blah(blah){}

    template <typename T>
    void operator()(T& t) const {
        t = blah;
    }

    int blah;
};

template <typename T>
void apply_for_each_to_assign(T &t)
{
    boost::fusion::for_each(t, F(6));
}

int main() {
    boost::fusion::vector<int, double, int> idi;
    apply_for_each_to_assign(idi);
}

我的问题是,不是用值 6 填充每个元素 - 让每个元素递增 1 的最简洁方法是什么?所以

v[0] = 1
v[1] = 2 

等等?我想我需要编写一个增量函数,但我不确定如何将它合并到上面的代码中?

最佳答案

您可以使用fold .

fold 采用函数 A f(A, B),其中 B 是您的元素类型,初始 A value 并在所有元素上调用它。它大致相当于 f(f(f(initial,first_elem), secondary_elem),third_elem)

你应该像这样声明仿函数:

struct accumulator
{
    typedef int result_type;

    template<typename T>
    int operator()(int value, T& t) const
    {
        t += value;
        return value + 1;
    }
};

用法如下:

template <typename T>
void apply_for_each_to_assign(T &t)
{
    boost::fusion::fold(t, 1, accumulator());        
}

这是一个完整的打印示例:

#include <boost/fusion/algorithm/iteration/fold.hpp>
#include <boost/fusion/algorithm/iteration/for_each.hpp>
#include <boost/fusion/include/fold.hpp>
#include <boost/fusion/container.hpp>
#include <iostream>

struct accumulator
{
    typedef int result_type;

    template<typename T>
    int operator()(int value, T& t) const
    {
        t += value;
        return value + 1;
    }
};

struct Print {
    template <typename T>
    void operator()(T& t) const {
        std::cout << t << std::endl;
    }
};

template <typename T>
void apply_for_each_to_assign(T &t)
{
    boost::fusion::fold(t, 1, accumulator());        
    boost::fusion::for_each(t, Print());
}

int main() 
{
    boost::fusion::vector<int, double, int> idi;
    apply_for_each_to_assign(idi);
}

关于c++ - 传入一个递增 boost::fusion:vector 元素的函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20685755/

相关文章:

c++ - 实时视频缓冲区访问网络摄像头,Windows Phone 8.1 C++

C++从文本文件中删除尾随的新行

c++ - 对更多 boost::intrusive 容器中的一个元素感到困惑

c++ - 通过从文件中读取来 boost 正则表达式匹配

C++ - getline stdin EOF 不工作

c++ - 用于大型/超大型数据集的支持 vector 机 (SVM)

c++ - 重载 << 运算符 C++ - 指向类的指针

c++ - 使用带有递归的 std::variant,而不使用 boost::recursive_wrapper

c++ - 使用 MinGW 构建 Boost 1.45

c++ - 使用 boost 时如何在 Visual Studio 中设置目录?