首页 > 解决方案 > 在 C++ 中的新用户定义函数中调用用户定义函数

问题描述

我想通过将 C++ 代码导入 R 来在 R 中运行这些函数。我使用sourceCppRRcpp包中的函数从*.cpp文件中加载函数。

但是,当我使用该功能时get_add_terms_lapply

get_add_terms_lapply(t = 20,gamma=0.5772,Nb=25.13274)

我收到以下错误:

Error in get_add_terms_lapply(t = time_end, gamma = gamma, Nb = Nb) : 
  negative length vectors are not allowed   

这是我使用的源 *.cpp 文件:

#include <Rcpp.h>
using namespace Rcpp;

// [[Rcpp::export]]
double get_add_terms(double i, double t, double Nb) {

  int j = i - 3;

  NumericVector x(j);
  double total = 0;

  if( j == 0){
  total = 0;
  }else{

  for(int u = 0; u <= j; u++) {
  int res = pow(u+1, 2.0);
  x[u] = res;
  }

  NumericVector::iterator it;
  for(it = x.begin(); it != x.end(); ++it) {
  total += *it;
  }

  }

  float log_term = pow(log(t - (0.5 + i - 2.0)), (i-1));
  double int_tot = (total / t);

  double exp_term = exp(-int_tot);
  double add_terms = (i * exp_term * log_term) / pow(Nb,(i-1));

return add_terms;

  }

// [[Rcpp::export]]
NumericVector get_add_terms_lapply(double t, double gamma, double Nb) {


    float term1 = ( 2.0 * log(t - 0.5) + (2.0 * gamma)) / Nb;

    double N;
    if (t == 1 || t == 2) {
    N = 2;
    }else{
    if (t <= 44) {
    N = t;
    }else{
    N = 44;
    }
    }

    NumericVector term_up(N);
    term_up[0] = 0;
    term_up[1] = term1;


    for(double i = 2; i < N; ++i) {
    term_up[i-1] = get_add_terms(i,  t, Nb);
    }
return term_up;
}

除了我在这里的具体示例之外,我想知道如何在 C++ 中的新用户定义函数中使用以前的用户定义函数。

标签: c++ruser-defined-functionsrcpp

解决方案


推荐阅读