犰狳的 print() 方法和 cout 在从 Rcpp 调用时顺序不一致
Armadillo's print() method and cout are inconsistent in order when called from Rcpp
最近,我一直在使用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 1n";
arma::mat X(n, n);
cout << "Print 2n";
X.print();
cout << "Print 3n";
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 的书和这篇 Rcpp 文章,解决方案是使用Rcout
而不是cout
和print()
。
根据德克的书:
因为 R 为我们的统计计算提供了"外壳", 程序需要将其(打印的(输出与使用 它自己的缓冲。
此外,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 1n";
arma::mat X(n, n);
Rcout << "Print 2n";
Rcout << X << "n";
Rcout << "Print 3n";
return 1;
}
相关文章:
- 如何防止 c++ 在从浮点型转换为双精度型(不适用于 IO)时添加额外的小数?
- phytec phyBOARD iMX-6在从闪存而不是SD卡运行qt5 opengles应用程序时表现不佳(FPS减半
- ifstream文件在从行中读取时被清除
- 有没有办法在从编译器获取参数时避免预处理器宏?
- gSoap在从.wsdl创建.h期间出现错误
- 如何在从抽象基派生的类中实现相同的方法?
- 犰狳的 print() 方法和 cout 在从 Rcpp 调用时顺序不一致
- 为什么向量内部的指针在从函数返回时会发生变化?
- 在从Qt调用的Python脚本中导入OpenCV崩溃
- 如何在从文件中读取整数时使用 file.eof()?
- 为什么 c++11 std::normal_distribution 在从函数调用时返回相同的模式?
- 错误:基类在从基类父派生类 Son 时未定义
- Rcpp:在 R 中调用 c++ 函数而不导出 c++ 函数
- 有没有办法在从临时返回按值string_view时获得编译器警告?
- "acceptor"在从TCP迁移到UDP时不是"boost::asio::ip::udp
- C++:如何在从给定缓存中排除数字的同时生成随机数
- 在从 C++ 转换为 C# 的代码中,我应该使用什么而不是 memcpy?
- 为什么 char 数组在从 C++ 中的函数返回时会丢失?
- C++ 安全数组在从 c# COM dll 返回时具有无效数据
- 在从仅移动类型派生的类中定义析构函数在使用 std::vector emplace_back或push_back创建时会