c++ - Handling List in Rcpp -
i trying take rcpp::charactermatrix , convert each row own element within rcpp::list.
however, function have written has odd behavior every entry of list corresponds last row of matrix. why so? pointer related concept? please explain.
function:
#include <rcpp.h> using namespace rcpp; // [[rcpp::export]] list char_expand_list(charactermatrix a) { charactervector b(a.ncol()); list output; for(int i=0;i<a.nrow();i++) { for(int j=0;j<a.ncol();j++) { b[j] = a(i,j); } output.push_back(b); } return output; } test matrix:
this matrix a passed above function.
mat = structure(c("a", "b", "c", "a", "b", "c", "a", "b", "c"), .dim = c(3l, 3l))
> mat [,1] [,2] [,3] [1,] "a" "a" "a" [2,] "b" "b" "b" [3,] "c" "c" "c" output:
above function should take matrix input , return list of rows of matrix so:
> char_expand_list(mat) [[1]] [1] "a" "a" "a" [[2]] [1] "b" "b" "b" [[3]] [1] "c" "c" "c" but instead getting different:
> char_expand_list(mat) [[1]] [1] "c" "c" "c" [[2]] [1] "c" "c" "c" [[3]] [1] "c" "c" "c"
now there reproducible example...
it very, very, bad use .push_back() on rcpp data types end copying , fro ever expanding object rcpp data types hide r object must recreated. result, should use std::list std::vector<t> type t (i.e. std::string). @ end, use rcpp::wrap return correct object.
e.g.
// [[rcpp::export]] rcpp::list char_expand_list(rcpp::charactermatrix a) { std::vector<std::string> b(a.ncol()); std::list<std::vector<std::string> > o; for(int i=0;i<a.nrow();i++) { for(int j=0;j<a.ncol();j++) { b[j] = a(i,j); } o.push_back(b); } return rcpp::wrap(o); } alternatively, aim keep rcpp::list, declare size expecting head of time , still use std::vector<t> element.
e.g.
// [[rcpp::export]] rcpp::list char_expand_list(rcpp::charactermatrix a) { std::vector<std::string> b(a.ncol()); rcpp::list o(a.nrow()); for(int i=0;i<a.nrow();i++) { for(int j=0;j<a.ncol();j++) { b[j] = a(i,j); } o[i] = b; } return o; } regarding main issue though, list attribute able store last pointer location. hence, repeated lines of "c" throughout list.
Comments
Post a Comment