2013-07-19 23 views
3

我很新手到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 

回答

0

我認爲沒有更短的路!

但你NumericVector subsetNumVec(NumericVector x, IntegerVector index)是容易出錯:

在這條線

out[i] = x[index[i]]; 

您訪問的載體,而不範圍檢查。因此,在平凡的情況下,x爲空或索引超出範圍,你得到一些不確定的行爲。

而且,你方法可以通過參考

NumericVector subsetNumVec(const NumericVector& x, const IntegerVector& index) 

調用沒有理由複製這兩種載體。您只需將減法index = index -1;設置爲out[i] = x.at(index[i] - 1);

此處,x.at(index[i] - 1)會引發錯誤索引。但你需要一些錯誤處理(返回空載體或外面做處理)。

1

如果使用犰狳矢量,而不是RCPP載體可以做到這一點。

Rcpp Gallery的具有post with a complete example:看到特別是第二示例。你的索引項必須在(簽名)uvecumat