簡體   English   中英

為什么我的Rcpp函數返回一個向量 <vector <int> &gt;崩潰?

[英]Why is my Rcpp function that returns a vector <vector <int>> crashing?

這是我的測試代碼

#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);
}

這是我的Rstudio會話的圖片。 你可以看到我的函數testVector崩潰了Rstudio。 我的外部標題中的任何其他函數都沒有問題。 就這一個!! :( Rstudio會話崩潰了

您的矢量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));

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM