Transform a boost::array into NumericVector in Rcpp

前端 未结 2 1080
清歌不尽
清歌不尽 2021-01-25 20:23

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

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

Now, I want to create a function to tra

2条回答
  •  心在旅途
    2021-01-25 20:44

    How about

    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);
    

    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);
    

提交回复
热议问题