我想我错过了一些相当基本的东西,但我不知道是什么:
#include <Rcpp.h>
using namespace Rcpp;
// [[Rcpp::export]]
NumericMatrix test(NumericVector x) {
for(int i=0; i<100; i++)
{
NumericMatrix n_m1(4,5);
}
return n_m1;
}
这给了我错误:
第 17 行“n_m1”未在此范围内声明
第19行控制到达非void函数的结尾[-Wreturn-type]
第一个错误显然是无稽之谈。它与循环有关,因为如果我删除它,它会工作得很好。
非常感谢任何帮助!
最佳答案
这个变量的范围(n_m1
):
for(int i=0; i<100; i++)
{
NumericMatrix n_m1(4,5);
}
是循环。所以当然在循环之外你不能使用它。 也不返回。
在方法级别扩展范围定义:
NumericMatrix test(NumericVector x) {
NumericMatrix n_m1(4,5);
for(int i=0; i<100; i++)
{
// you can use it here now
}
return n_m1; // also here
}
我在上面定义变量的方式现在它具有函数范围 - 例如,您只能在函数内部使用它。如果想进一步扩大范围,或许可以考虑全局变量?如果有兴趣,您可以阅读有关该主题的更多信息,例如 here
关于c++ - Rcpp:无法返回在循环中创建的对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28583817/