c++ - 如何从 C++ 中的 NumericVector 中提取多个值

标签 c++ r indexing rcpp

对于 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

这是我目前使用 sourceCpp 在 R 中执行的 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

最佳答案

如果您使用 Armadillo vector 而不是 Rcpp vector ,则可以执行此操作。

Rcpp Gallery有一个post with a complete example :特别是第二个例子。您的索引条目必须在(未签名的)uvecumat 中。

关于c++ - 如何从 C++ 中的 NumericVector 中提取多个值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17743746/

相关文章:

c++ - C 程序的执行方式与 shell 不同

c++ - CMake:使静态库有效但动态库无效

r - 将变量值 reshape 为列的最快​​方法

regex - 特殊字符后的首字母大写

r - 如何制作漂亮的定性条形组成图

mysql - 复合索引中列的顺序会影响查找速度吗?

python - 需要在 python 中使用字符串索引的帮助

c++ - 您如何计算内存访问时间?

c++ - 离散数学到 C++

mysql - 慢速 MySQL 查询的索引