我很新手到Rcpp
和其功能,更何況C++本身,所以這可能看起來微不足道如果您是專家。然而,沒有這樣的事情作爲一個愚蠢的問題,所以無論如何:如何從NumericVector用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