c++ - 从Rcpp调用时, Armadillo 的print()方法和cout顺序不一致

标签 c++ r rcpp armadillo rcpparmadillo

最近,我一直在使用 RcppArmadillo,但我注意到某些对象的打印顺序存在一些不一致。特别是使用 coutprint() 时。有时,会先打印 print(),然后打印 cout;有时则相反。

我不明白为什么会发生这种情况。我认为 coutprint() 是异步调用的,因此顺序不同,但为什么会发生这种情况呢?又该如何预防呢?

示例

如果我有以下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 bookthis Rcpp article ,解决方案是使用 Rcout 代替 coutprint()

根据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/

相关文章:

c++ - 从指针 C++ 获取对象

C++ 设计容器和管理列表返回

c++ - *this-> 不能作为函数使用

Rcpp:在处理 NumericMatrix 时,* 的语法糖会产生意想不到的结果

c++ - 在Qt中,如何确定屏幕的大小?

r - 使用 R 查找范围内的重叠

r - 自举 nls 拟合不良数据期间出现奇异梯度错误

r - R中近似子串匹配的位置

r - 在 Windows 上编写 R 包构建二进制文件

c++ - 将 Python 翻译成 Rcpp