Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/r/69.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C++ 为什么我的Rcpp函数返回一个向量<;向量<;int>&燃气轮机;撞车?_C++_R_Rcpp - Fatal编程技术网

C++ 为什么我的Rcpp函数返回一个向量<;向量<;int>&燃气轮机;撞车?

C++ 为什么我的Rcpp函数返回一个向量<;向量<;int>&燃气轮机;撞车?,c++,r,rcpp,C++,R,Rcpp,这是我的测试代码 #include <Rcpp.h> using namespace Rcpp; #include "/Users/jjunju/Documents/R/accum/accum.h" // Below is a simple example of exporting a C++ function to R. You can // source this function into an R session using the Rcpp::sourceCpp //

这是我的测试代码

#include <Rcpp.h>
using namespace Rcpp;

#include "/Users/jjunju/Documents/R/accum/accum.h"

// Below is a simple example of exporting a C++ function to R. You can
// source this function into an R session using the Rcpp::sourceCpp 
// function (or via the Source button on the editor toolbar)

// For more on using Rcpp click the Help button on the editor toolbar

// [[Rcpp::export]]
int timesTwo(int x) {
   return x * 2;
}

// [[Rcpp::export]]
void testExternalHeader(){
  matrix <int> test(3,3);
  test.Print();
}

// [[Rcpp::export]]
vector<vector <int> > testVector(){
  vector<vector <int> > a;
  a.resize(3); //rows
  for(int i=0;i<3;i++){
    a.resize(3); //cols
    for(int j=0;j<3;j++){
    a[i][j]=i*3+j;
    }
  }
  return(a);
}
#包括
使用名称空间Rcpp;
#包括“/Users/jjunju/Documents/R/accum/accum.h”
//下文是将C++函数导出到R的简单示例。
//使用Rcpp::sourceCpp将此函数源化到R会话中
//函数(或通过编辑器工具栏上的“源”按钮)
//有关使用Rcpp的详细信息,请单击编辑器工具栏上的“帮助”按钮
//[[Rcpp::导出]]
整数倍二(整数倍){
返回x*2;
}
//[[Rcpp::导出]]
void testerExternalHeader(){
矩阵检验(3,3);
test.Print();
}
//[[Rcpp::导出]]
向量testVector(){
载体a;
a、 调整大小(3);//行

对于(int i=0;i您的向量
a
包含3个空向量,但您将它们视为不在此处:

a[i][j]=i*3+j; // a[i] has size 0 here
这种越界访问是未定义的行为。原因是

a.resize(3); //cols
不是你想象的那样。它基本上没有效果,因为
a
在这个阶段已经是3号了

如果需要一个3乘3的向量,请按如下方式初始化
a

vector<vector <int> > a(3, std::vector<int>(3));
向量a(3,std::向量(3));
我发现我应该在循环中键入'a[I].resize(3)')。它现在可以工作,但在R in中返回的是列表而不是矩阵!>'testVector()[[1][1]0 1 2[[2][1]3 4 5[[3][1]6 7 8'@jjunju好的。如果你按照我的建议,你不必调用
resize
,但我不知道如何将嵌套向量返回到R。如果你想要一个3x3,只需创建Rcpp::numerimatrix(3,3)。这些返回到R就可以了。谢谢@DirkEddelbuettel