将boost :: array转换为Rcpp中的NumericVector [英] Transform a boost::array into NumericVector in Rcpp

查看:108
本文介绍了将boost :: array转换为Rcpp中的NumericVector的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我的C ++脚本(使用Rcpp在R中运行)中,我定义了:

In my C++ script (run in R using Rcpp), I defined :

typedef boost::array< double ,3 > state_type;

现在,我想创建一个将state_type变量转换为Rcpp :: NumericVector变量的函数,以及一个与之相反的函数.那怎么办 为了将R函数用于C ++,我需要这样做.

Now, I want to create a function to transform a state_type variable to a Rcpp::NumericVector variable, and another function that do the inverse. How can do that? I need to do that in order to use R function into C++.

推荐答案

如何

Rcpp::NumericVector boost_array_to_nvec(state_type const& s) {
    Rcpp::NumericVector nvec(s.size());
    for (size_t i = 0; i < s.size(); ++i) {
        nvec[i] = s[i];
    }
    return nvec;
}
state_type nvec_to_boost_array(Rcpp::NumericVector const& nvec) {
    state_type s;
    for (size_t i = 0; i < s.size(); ++i) {
        s[i] = nvec[i];
    }
    return s;
}
...
state_type s {0,0,0};
Rcpp::NumericVector nvec = boost_array_to_nvec(s);
s = nvec_to_boost_array(nvec);

如果您必须多次执行此操作.这可能不是进行转换的最有效方法.但是现在您必须查看nvec已分配给正确的大小.

If you have to do this a lot of times. This might not be the most efficient way of doing the transformation. But now you have to look that nvec is already allocated to the correct size.

void boost_array_to_nvec(state_type const& s, Rcpp::NumericVector& nvec) {
    for (size_t i = 0; i < s.size(); ++i) {
        nvec[i] = s[i];
    }
}
void nvec_to_boost_array (Rcpp::NumericVector const& nvec, state_type& s) {
    for (size_t i = 0; i < s.size(); ++i) {
        s[i] = nvec[i];
    }
}
...
state_type s {0,0,0};
Rcpp::NumericVector nv(3);
boost_array_to_nvec(s, nv);
nvec_to_boost_array(nv, s);

这篇关于将boost :: array转换为Rcpp中的NumericVector的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆