Oto mój kod testowy
#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);
}
Oto zdjęcie mojej sesji Rstudio. Widać, że moja funkcja testVector zawiesza Rstudio. Nie mam problemów z żadnymi innymi funkcjami z mojego zewnętrznego nagłówka. Tylko ten !! :(
Odpowiedzi:
2 dla odpowiedzi № 1Twój wektor a
zawiera 3 puste wektory, ale traktujesz je tak, jakby ich tu nie było:
a[i][j]=i*3+j; // a[i] has size 0 here
Ten dostęp poza granicami jest niezdefiniowanym zachowaniem. Powodem jest to, że to
a.resize(3); //cols
nie jest tym, czym myślisz. Zasadniczo nie ma to żadnego wpływu, ponieważ a
ma już rozmiar 3 na tym etapie.
Jeśli chcesz wektor 3 na 3 wektorów, zainicjuj a
lubię to:
vector<vector <int> > a(3, std::vector<int>(3));