如何使用boost元组返回两个向量

时间:2016-11-15 03:34:49

标签: python c++ boost

我将python代码重写为C ++并遇到了问题。我在python中创建了一个函数:

from my_vec import Vector

def param(gamma):

    coeff = Vector(6)
    exp = Vector(6)

    if abs(gamma - 0.3) < 1E-6:
        coeff[0] =  33;   exp[0] =   0.1;
        coeff[1] =  -33;  exp[1] =  2.2;
        coeff[2] =  21;   exp[2] =   0.16;
        coeff[3] =  23;   exp[3] =   3.312;
        coeff[4] =  23;   exp[4] =   100;
        coeff[5] =  32;   exp[5] =  59.00;
    elif abs(gamma - 0.4) < 1E-6:
        coeff[0] =  -0.23;  exp[0] =   0.02;
        coeff[1] =  -0.48;  exp[1] =   0.18;
        coeff[2] =   200;  exp[2] =    1.82;
        coeff[3] =   200;  exp[3] =    3.71;
        coeff[4] =   200;  exp[4] =   14.28;
        coeff[5] =   0.00;  exp[5] =  79.11;

    return coeff, exp

随后,我尝试在C ++中编写相同的用法。似乎使用元组是我正在寻找的东西。 但是,我之前没有使用它,而且我正在努力完成这项任务。

我创建了:

    std::vector<float> coef1 = {-0.366770, -0.249990, -0.411230, 0.144690, -0.101790, 0.010510};
    std::vector<float> exp1 = {0.02, 1.910630, 0.16492, 3.31721, 10.45634, 59.3438};
    std::vector<float> coef2 = {-0.36, -0.24, -0.41, 0.14, -0.10, 0.01};

    std::vector<float> exp2 = {0.02, 1.23, 12, 3.31, 11, 22};

    typedef boost::tuple<std::vector<float>, std::vector<float>> parameters;
       parameters param1{coef1, exp1};
       parameters param2{coef2, exp2};

此时,我喜欢创造像if abs(gamma - 0.3) < 1E-6等条件的结束返回系数和exp向量。如何创建一个用python编写的函数?

1 个答案:

答案 0 :(得分:1)

这是一个快速翻译.¹

包含<cmath>和使用std::abs对于获取abs的浮点版本至关重要。

<强> Live On Coliru

#include <tuple>
#include <vector>
#include <cmath>

using vec6 = std::array<double, 6>;
using params = std::tuple<vec6, vec6>;

params param(double gamma) {
    using std::abs; // enable ADL in case you use e.g. boost::multiprecision as the vector element type
    if (abs(gamma - 0.3) < 1E-6) {
        return std::make_tuple ( 
                vec6{{-0.366770, -0.249990, -0.411230, 0.144690, -0.101790, 0.010510}}, // coeff1
                vec6{{0.02, 1.910630, 0.16492, 3.31721, 10.45634, 59.3438}} ); // exp1
    }
    if (abs(gamma - 0.4) < 1E-6) {
        return std::make_tuple ( 
                vec6{{-0.36, -0.24, -0.41, 0.14, -0.10, 0.01}}, // coeff2
                vec6{{0.02, 1.23, 12, 3.31, 11, 22}} ); // exp2
    }

    throw std::runtime_error("unhandled gamma");
}

int main() {
    auto p = param(0.4);
}

¹使用暂定C ++版本的值,而不是python版本