Hi, I am familiar with R but quite new to C++. I am reading a C++ textbook, so if this is an obvious question just resulting in my ignorance of C++, please let me know.
I tried to translate someone else's R loop that was slow into c++ to use with Rcpp and the inline package: require(Rcpp) require(inline) ## Rcpp function body src <- ' NumericVector xx(x); int n = xx.size(); NumericVector res(xx); int toggle = 0; int tot = 100; int max = 100; typedef NumericVector::iterator vec_iterator; vec_iterator ixx = xx.begin(); vec_iterator ires = res.begin(); for (int i = 0; i < n; i++) { if (ixx[i] != 0) { if (toggle == 1) { ires[i] = 0; } if (toggle != 1) { tot += ixx[i]; if (tot > max) { max = tot; } if (tot <= max) { if (.98 * max > tot) { toggle = 1; } } } } if (ixx[i] == 0) { tot = 100; max = 100; toggle = 0; } } return res; ' ## compile the function foo.rcpp <- cxxfunction(signature(x = "numeric"), src, plugin = "Rcpp") ## here is a little input vector, the function should ## output the same but with a 0 instead of 8 > d [1] 0 0 0 1 3 4 5 -1 2 3 -5 8 > foo.rcpp(d) # great it works! [1] 0 0 0 1 3 4 5 -1 2 3 -5 0 > d # but now d itself has changed? [1] 0 0 0 1 3 4 5 -1 2 3 -5 0 It seems particularly surprising to me, because I do not think I even modify the input vector, I copy it into the numeric vector res and alter that. Thanks, Josh -- Joshua Wiley Ph.D. Student, Health Psychology Programmer Analyst II, Statistical Consulting Group University of California, Los Angeles https://joshuawiley.com/ _______________________________________________ Rcpp-devel mailing list Rcpp-devel@lists.r-forge.r-project.org https://lists.r-forge.r-project.org/cgi-bin/mailman/listinfo/rcpp-devel