下面的玩具例子同居parallelFor
工作正常(f2
是f1
的並行版本):RcppArmadillo和RcppParallel
// [[Rcpp::depends(RcppParallel)]]
// [[Rcpp::depends(RcppArmadillo)]]
#include <RcppArmadillo.h>
#include <RcppParallel.h>
#include <iostream>
#define vector NumericVector
using namespace Rcpp;
using namespace RcppParallel;
// compute values i/i+1 for i = 0 to n-1
// [[Rcpp::export]]
vector f1(int n) {
vector x(n);
for(int i = 0; i < n; i++) x[i] = (double) i/ (i+1);
return x;
}
struct mytry : public Worker {
vector output;
mytry(vector out) : output(out) {}
void operator()(std::size_t begin, std::size_t end) {
for(int i = begin; i < end; i++) output[i] = (double) i/ (i+1);
}
};
// [[Rcpp::export]]
vector f2(int n) {
vector x(n);
mytry A(x);
parallelFor(0, n, A);
return x;
}
但是,如果我取代#define vector NumericVector
通過#define vector arma::vec
這不起作用了。代碼編譯並運行,f1
沒問題,但由f2
返回的向量只包含未初始化的值。
非常感謝您的任何澄清。
應該將'arma :: vec'作爲該類的參考成員嗎? (這適用於'Rcpp'情況,因爲R的向量只是指針上的代理對象,所以你仍然可以訪問相同的對象) – 2014-10-07 15:42:58
謝謝,我會嘗試。 – Elvis 2014-10-07 20:41:46
@KevinUshey沒關係,兩個放置好的'&'並運行:準確地說,用'mytry'(vector out)替換vector vector;'mytry(vector out):'output (vector&out):output(out){}'。你會將你的評論作爲答案嗎?我很高興接受它。因爲有一天我不太可能成爲唯一能夠解決這個問題的新手,我認爲這是值得的。 – Elvis 2014-10-08 07:30:07