2016-11-15 18 views
1

我正在將一個python代碼重寫爲C++並遇到了問題。我在python中創建了一個函數:如何使用boost元組來返回兩個向量

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編寫的函數?

+0

什麼是你的問題? –

+0

而你的問題是? – Ari0nhh

+0

已更新。希望它是有道理的 – Monica

回答

1

這裏有一個快速translate.¹

有一個微妙的地步<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版本

+0

非常感謝!它有很多幫助。但是,我還有一個問題。我已經解包了我的參數(coeff和exp)。你能給我一個提示怎麼做嗎?我已經厭倦了使用領帶並得到,但沒有運氣。 – Monica

+1

'tie'方法。 http://coliru.stacked-crooked.com/a/e8479d1796c37ebc 'get'方法。 http://coliru.stacked-crooked.com/a/283ca17d521a292a – sehe

+1

cppreference.com有優秀的樣本http://en.cppreference.com/w/cpp/utility/tuple/tie或http://en.cppreference。 com/w/cpp/utility/tuple/get – sehe

相關問題