【发布时间】:2013-07-19 10:20:43
【问题描述】:
对于Rcpp 及其功能,我还是个新手,更不用说 C++ 本身了,所以对于你们当中的专家来说,这可能看起来微不足道。但是,没有愚蠢的问题,所以无论如何:
我想知道是否有一种方法可以在 C++ 中使用索引同时处理 NumericVector 的多个元素。为了让整个事情更清楚,这是我正在尝试做的 R 等价物:
# Initial vector
x <- 1:10
# Extract the 2nd, 5th and 8th element of the vector
x[c(2, 5, 8)]
[1] 2 5 8
这是我目前在 R 中使用 sourceCpp 执行的 C++ 函数中得到的结果。它有效,但对我来说似乎很不方便。有没有更简单的方法来实现我的目标?
#include <Rcpp.h>
using namespace Rcpp;
// [[Rcpp::export]]
NumericVector subsetNumVec(NumericVector x, IntegerVector index) {
// Length of the index vector
int n = index.size();
// Initialize output vector
NumericVector out(n);
// Subtract 1 from index as C++ starts to count at 0
index = index - 1;
// Loop through index vector and extract values of x at the given positions
for (int i = 0; i < n; i++) {
out[i] = x[index[i]];
}
// Return output
return out;
}
/*** R
subsetNumVec(1:10, c(2, 5, 8))
*/
> subsetNumVec(1:10, c(2, 5, 8))
[1] 2 5 8
【问题讨论】: