gpt4 book ai didi

rcpp - 在 Rcpp 中声明一个变量作为引用

转载 作者:行者123 更新时间:2023-12-04 22:55:39 28 4
gpt4 key购买 nike

在 C++ 中,我们可以声明一个变量作为引用。

int a = 10;
int& b = a;

如果我们设置 b=15a 也会改变。

我想在 Rcpp 中做类似的事情。
List X = obj_from_R["X"];
IntegerVector x_i = X[index];
x_i = value;

我想通过向其向量之一插入一个值来更新 R 中名为 X 的对象。上面的代码不起作用,所以我尝试了这个:
IntegerVector& x_i = X[index];

并收到一个错误。
error: non-const lvalue reference to type 'IntegerVector'
(aka 'Vector<13>') cannot bind to a temporary of type 'Proxy' (aka 'generic_proxy<19>')

最佳答案

这个问题在不同的变体中被问到很多。

以下是一些流行的答案:

  • Within C++ functions, how are Rcpp objects passed to other functions (by reference or by copy)?
  • Update Rcpp::NumericMatrix passed by reference using RcppArmadillo submat()
  • Rcpp pass by reference vs. by value
  • Passing by reference a data.frame and updating it with rcpp
  • Rcpp Update matrix passed by reference and return the update in R
  • Passing large matrices to RcppArmadillo function without creating copy (advanced constructors)
  • Rcpp: Inconsistent behavior with proxy model
  • Why is my Rcpp implementation for finding the number of unique items slower than base R?


  • 更多细节...

    从我写的常见问题条目 Rcpp changed the (const) object I passed by value :

    Rcpp objects are wrappers around the underlying R objects' SEXP, or S-expression. The SEXP is a pointer variable that holds the location of where the R object data has been stored R:Internals. That is to say, the SEXP does not hold the actual data of the R object but merely a reference to where the data resides. When creating a new Rcpp object for an R object to enter C++, this object will use the same SEXP that powers the original R object if the types match otherwise a new SEXP must be created to be type safe. In essence, the underlying SEXP objects are passed by reference without explicit copies being made into C++. We refer to this arrangement as a proxy model.



    因此, & 只是可视化的糖,因为 Rcpp 对象已经作为引用。

    因此,以下将显示结论:
    #include <Rcpp.h>

    // [[Rcpp::export]]
    void show_references(Rcpp::List X,
    Rcpp::IntegerVector y,
    int index = 0) {
    X[index] = y;
    }

    例子:
    y_vec = c(-1L, 8L, 12L)
    X_list = list(a = c(0L, 2L, 3L), b = c(42L, 50L, 30L))
    X_list
    # $a
    # [1] 0 2 3
    #
    # $b
    # [1] 42 50 30

    show_references(X_list, y_vec)
    X_list
    # $a
    # [1] -1 8 12
    #
    # $b
    # [1] 42 50 30

    我创建的以下 Rcpp 代理模型幻灯片应该进一步说明正在发生的事情

    enter image description here
    enter image description here

    enter image description here
    enter image description here

    资料来源: https://twitter.com/axiomsofxyz/status/938881541396197377

    关于rcpp - 在 Rcpp 中声明一个变量作为引用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48363076/

    28 4 0
    Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
    广告合作:1813099741@qq.com 6ren.com