R在评估Rcpp功能时崩溃 < >为了减少我的代码运行时间,我需要使用RCPP在C++中实现背包求解器功能。当我从R调用C++函数时,它工作了最初几次,但是如果我反复调用它(RealStudio)崩溃(在前3到10次内,我调用函数)。我有3年的R经验,但没有C++。背包解算器功能如下: #include <Rcpp.h> using namespace Rcpp; // [[Rcpp::export]] // A function that returns maximum of two integers int max(int a, int b) { return (a > b)? a : b; } // Returns the solution of the Knapsack problem // [[Rcpp::export]] IntegerVector knapSack(int nItems, int size, NumericVector weights, NumericVector values){ NumericMatrix matrix(nItems,size); NumericMatrix picks(nItems,size); IntegerVector chosen(nItems); int i,j; for (i=1;i<=nItems;i++){ for (j=0;j<=size;j++){ if (weights(i-1)<=j){ matrix(i,j) = max(matrix(i-1,j),values(i-1)+matrix(i-1,j-weights(i-1))); if (values(i-1)+matrix(i-1,j-weights(i-1))>matrix(i-1,j)) picks(i,j)=1; else picks(i,j)=-1; } else{ picks(i,j) = -1; matrix(i,j) = matrix(i-1,j); } } } while (nItems>0){ if (picks(nItems,size)==1){ nItems--; chosen(nItems)=1; size -= weights(nItems); } else{ nItems--; } } return chosen; }

R在评估Rcpp功能时崩溃 < >为了减少我的代码运行时间,我需要使用RCPP在C++中实现背包求解器功能。当我从R调用C++函数时,它工作了最初几次,但是如果我反复调用它(RealStudio)崩溃(在前3到10次内,我调用函数)。我有3年的R经验,但没有C++。背包解算器功能如下: #include <Rcpp.h> using namespace Rcpp; // [[Rcpp::export]] // A function that returns maximum of two integers int max(int a, int b) { return (a > b)? a : b; } // Returns the solution of the Knapsack problem // [[Rcpp::export]] IntegerVector knapSack(int nItems, int size, NumericVector weights, NumericVector values){ NumericMatrix matrix(nItems,size); NumericMatrix picks(nItems,size); IntegerVector chosen(nItems); int i,j; for (i=1;i<=nItems;i++){ for (j=0;j<=size;j++){ if (weights(i-1)<=j){ matrix(i,j) = max(matrix(i-1,j),values(i-1)+matrix(i-1,j-weights(i-1))); if (values(i-1)+matrix(i-1,j-weights(i-1))>matrix(i-1,j)) picks(i,j)=1; else picks(i,j)=-1; } else{ picks(i,j) = -1; matrix(i,j) = matrix(i-1,j); } } } while (nItems>0){ if (picks(nItems,size)==1){ nItems--; chosen(nItems)=1; size -= weights(nItems); } else{ nItems--; } } return chosen; },r,crash,rcpp,R,Crash,Rcpp,我的操作系统是Windows7,我有R版本3.2.0和Rstudio 0.98.1102。提前谢谢你的帮助 最明显的问题是数组访问问题;检查是否有适当的0-vs 1索引,以及是否超过了向量的边界。您误解了StackOverflow的用途。我们不是“hey debug my function for me”服务,所以希望这个问题很快解决。 library(Rcpp) sourceCpp('<path>/Cfunction.cpp') nrRespondents <- 1000

我的操作系统是Windows7,我有R版本3.2.0和Rstudio 0.98.1102。提前谢谢你的帮助

最明显的问题是数组访问问题;检查是否有适当的0-vs 1索引,以及是否超过了向量的边界。您误解了StackOverflow的用途。我们不是“hey debug my function for me”服务,所以希望这个问题很快解决。
library(Rcpp)
sourceCpp('<path>/Cfunction.cpp')
nrRespondents <- 1000
nrComponents <- 30
prices <- matrix(sample(0:100, (nrRespondents*nrComponents), replace=T),nrow=nrRespondents, ncol=nrComponents) 
budgets <- matrix(sample(300:500, nrRespondents, replace=T),nrow=nrRespondents, ncol=1) 
utilities <- matrix(sample(0:100, nrRespondents*nrComponents, replace=T),nrow=nrRespondents, ncol=nrComponents) 
i <- sample(100,1)
b <- budgets[i] #size
p <- prices[i,] #weights 
mu <- utilities[i,]
v <- mu-p #values
knapSack(nrComponents,b,p,v)