最近,我一直在使用 RcppArmadillo
,但我注意到某些对象的打印顺序存在一些不一致。特别是使用 cout
和 print()
时。有时,会先打印 print()
,然后打印 cout
;有时则相反。
我不明白为什么会发生这种情况。我认为 cout
和 print()
是异步调用的,因此顺序不同,但为什么会发生这种情况呢?又该如何预防呢?
示例
如果我有以下test_order.cpp
文件
#include <RcppArmadillo.h>
// [[Rcpp::depends(RcppArmadillo)]]
using namespace Rcpp;
using namespace arma;
// [[Rcpp::export]]
int test(int n){
cout << "Print 1\n";
arma::mat X(n, n);
cout << "Print 2\n";
X.print();
cout << "Print 3\n";
return 1;
}
并像这样从 R 调用它
library(Rcpp)
sourceCpp("test_order.cpp")
test(3)
打印时我得到不同的结果。三种不同的结果如下:
> test(3)
2.1220e-314 0 6.9531e-310Print 1
Print 2
2.3044e-314 6.9275e-310 6.9532e-310
2.1916e-314 2.1916e-314 2.2718e-314
Print 3
[1] 1
> test(3)
Print 1
Print 2
6.9531e-310 2.3044e-314 4.9407e-324
6.9532e-310 2.1916e-314 4.9407e-324
0 6.9275e-310 4.9407e-324
Print 3
[1] 1
> test(3)
6.9531e-310 2.3044e-314 4.9407e-324
6.9532e-310 2.1916e-314 4.9407e-324
0 6.9275e-310 4.9407e-324Print 1
Print 2
[1]Print 3
1
最佳答案
基于Roland的和 Dirk的评论,以及Dirk's book和 this Rcpp article ,解决方案是使用 Rcout
代替 cout
和 print()
。
根据Dirk's book :
Because R provides the “shell” around our statistical computing, programs need to synchronize their (printed) output with R which uses its own buffering.
此外,CRAN 维护者标记包含 std::cout
的代码。
因此 test_order.cpp
文件应如下所示:
#include <RcppArmadillo.h>
// [[Rcpp::depends(RcppArmadillo)]]
using namespace Rcpp;
using namespace arma;
// [[Rcpp::export]]
int test(int n){
Rcout << "Print 1\n";
arma::mat X(n, n);
Rcout << "Print 2\n";
Rcout << X << "\n";
Rcout << "Print 3\n";
return 1;
}
关于c++ - 从Rcpp调用时, Armadillo 的print()方法和cout顺序不一致,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60079107/