c++ - Rcpp:无法返回在循环中创建的对象

标签 c++ rcpp

我想我错过了一些相当基本的东西,但我不知道是什么:

    #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/

相关文章:

C++正在从不同的线程写入和读取变量未定义的行为

c++ - 确保只构建智能指针

android - 从android原生库获取原始dex文件

具有 Rcpp::Function 成员的 C++ 类

c++ - 函数没有导致错误,但它不会返回到程序

c++ - 模板类相互使用会产生歧义错误

c++ - R(macos 10.8.5),RcppArmadillo : can not find armadillo library or symbol _wrapper_ddot_

c++ - Rcpp 枚举支持

c++ - Rcpp:将 C++ 函数移植到 R,找不到 'Rcpp.h' 文件

c++ - 在 Windows 下编译 RInside 示例时出错