c++ - 分配大 vector 的问题

标签 c++ r rcpp rinside

我有以下程序。

#include <iostream>
#include <vector>
#include <algorithm>
#include <cassert>
#include <ctime>
#include <cmath>
#include <RInside.h>
using std::cout;
using std::endl;
using std::vector;
using namespace Rcpp;
int main(int argc, char** argv){
    RInside R;
    R.parseEvalQ("set.seed(1)"); Rcpp::RNGScope();
    const Function sample("sample");
    vector<int> vv = as<vector<int> >(sample(NumericVector::create(0,1,2,3), 1e6, true,NumericVector::create(.3,.3,.2,.2)));
    cout<<"1"<<endl<<std::flush;
    const vector<int> vv2 = as<vector<int> >(sample(NumericVector::create(0,1,2,3), 2e6, true,NumericVector::create(.3,.3,.2,.2)));
    cout<<"2"<<endl;
}

输出是

1
Segmentation fault

这意味着 C++ vector vv2 无法初始化。为什么vv2不能赋值?

使用内联,这是我得到的:

> body <- '
+ using namespace Rcpp;
+ using std::vector;
+ using std::cout;
+ using std::endl;
+      Rcpp::RNGScope();
+     const Function sample("sample");
+     vector<int> vv = as<vector<int> >(sample(NumericVector::create(0,1,2,3), 1e6, true,NumericVector::create(.3,.3,.2,.2)));
+     cout<<"1"<<endl<<std::flush;
+     const vector<int> vv2 = as<vector<int> >(sample(NumericVector::create(0,1,2,3), 2e6, true,NumericVector::create(.3,.3,.2,.2)));
+     cout<<"2"<<endl;
+     List vecs(2);
+     vecs[1]=vv;
+     vecs[1]=vv2;
+     return(vecs);
+     '
> require( inline )
Loading required package: inline
> require( Rcpp )
Loading required package: Rcpp
Loading required package: int64
> 
> signatures <- NULL
> fx <- cxxfunction( signatures, body, plugin = "Rcpp" )
> a <- fx()

 *** caught segfault ***
address 0x7f2b850eb013, cause 'memory not mapped'

Traceback:
 1: .Primitive(".Call")(<pointer: 0x7f2b8627d2c0>)
 2: fx()

Possible actions:
1: abort (with core dump, if enabled)
2: normal R exit
3: exit R without saving workspace
4: exit R saving workspace

最佳答案

你能在你的机器上用 R 做同样的事情吗? 200万个元素是相当多的。

此外,我几乎从不以这种方式回调 R 函数,因为它效率低下。如果您想加快速度,请用 C++ 重新实现 sample(),这不会太难。

接下来,我还建议首先通过内联尝试使用更简单的表达式。

最后,我听起来像是一张破唱片,试试 rcpp-devel 列表。

关于c++ - 分配大 vector 的问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8352089/

相关文章:

c++ - 将 const 引用传递到构造函数链中

c++ - 这个嵌套数组是使用栈内存还是堆内存?

r - 在不运行的情况下检查 R 脚本的语法

r - 使用plyr绘制多个不同组的密度图(基于因子水平)

c++ - 使用 Rcpp 公开 C++ 类

c++ - 我是否需要在描述文件中为使用它的 R 包导入 RccpEigen,或者 "LinkingTo"就足够了吗?

c++ - 递归:使用传入参数的值

c++ - 在 C++ 中,返回时使用 move 操作是什么意思?

string - R中用空格分割不均匀字符串

c++ - C++ 函数相互调用时的 Rcpp 集成