我们一直在使用 RcppArmadillo
中的 sample
函数来随机采样 NumericVector
对象。但是,我们注意到不可能在 Armadillo 类型(vec
或 uvec
)上使用相同的函数。我们已经查看了 sample.h
文件中的函数定义,它看起来像一个应该能够使用这些类型的模板函数,但我们还无法弄清楚如何制作它可以与 Armadillo 类一起使用,而无需在 Rcpp
库中的 NumericVector
或 IntegerVector
类型之间进行大量转换。
例如,我们将此函数编写在名为 try.cpp
的文件中。
// [[Rcpp::depends(RcppArmadillo)]]
#include <RcppArmadillo.h>
#include <RcppArmadilloExtensions/sample.h>
using namespace arma;
using namespace Rcpp;
// [[Rcpp::export]]
arma::uvec sample_index(const int &size){
arma::uvec sequence = linspace<uvec>(0, size-1, size);
arma::uvec out = sample(sequence, size, false);
return out;
}
运行上面的代码会产生以下错误:
src/try.cpp|11 col 22 error| no matching function for call to 'sample' [cpp/gcc]
~/Library/R/3.3/library/Rcpp/include/Rcpp/sugar/functions/sample.h|401 col 1 error| note: candidate function not viable: no known conversion from 'arma::uvec' (aka 'Col<unsigned int>') to 'int' for 1st argument [cpp/gcc]
~/Library/R/3.3/library/Rcpp/include/Rcpp/sugar/functions/sample.h|437 col 1 error| note: candidate template ignored: could not match 'Vector' against 'Col' [cpp/gcc]
对此的任何帮助将不胜感激:)
最佳答案
如果将来有人遇到此问题,该问题似乎与正在使用的命名空间中 sample
函数的多个定义有关。具体地输入定义所需函数的 namespace 可以解决问题。特别是,需要从 Rcpp::RcppArmadillo
调用 sample
函数。
以下代码可按预期工作。
// [[Rcpp::depends(RcppArmadillo)]]
#include <RcppArmadillo.h>
#include <RcppArmadilloExtensions/sample.h>
// [[Rcpp::export]]
arma::uvec sample_index(const int &size){
arma::uvec sequence = arma::linspace<arma::uvec>(0, size-1, size);
arma::uvec out = Rcpp::RcppArmadillo::sample(sequence, size, false);
return out;
}
关于c++ - Armadillo vector 类的 RcppArmadillo 样本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43353109/