gpt4 book ai didi

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

转载 作者:太空狗 更新时间:2023-10-29 23:05:51 24 4
gpt4 key购买 nike

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

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com