gpt4 book ai didi

c++ - Rcpp map /字典/列表

转载 作者:塔克拉玛干 更新时间:2023-11-03 00:44:43 27 4
gpt4 key购买 nike

如何将 R 中的 map /字典/列表作为参数传递给 C++ 函数?

例如,我想做如下的事情:

#include <Rcpp.h>
using namespace Rcpp;

// [[Rcpp::export]]
int test(List map) {
int val = map["test"];
return(val);
}

/*** R
map <- list(test = 200, hello = "a")
test(map)
*/

输出应该是 200。

最佳答案

我在 Mac OS X 上遇到了类似的问题。运行您的代码片段似乎总是返回 1。但是,如果我按以下方式修改代码,它会起作用:

#include <Rcpp.h>
using namespace Rcpp;

// [[Rcpp::export]]
int test(List map) {
int val = as<int>( map["test"] );
return(val);
}

/*** R
map <- list(test = 200, hello = "a")
test(map)
*/

似乎类型推断出了问题——编译器应该“知道”这一点,因为我们正在将 map["test"] 分配给 int-声明的变量,它应该被转换为int,但事实似乎并非如此。所以,为了安全起见——一定要 as 任何来自 R 列表的内容。

此外,值得一提的是:在 R 中,200 是一个 double;如果你想显式传递一个 int,你应该写成 200L

FWIW,我正在使用 clang++ 进行编译:

> clang++ -v
Apple LLVM version 4.2 (clang-425.0.28) (based on LLVM 3.2svn)
Target: x86_64-apple-darwin12.4.0
Thread model: posix

> sessionInfo()
R version 3.0.0 (2013-04-03)
Platform: x86_64-apple-darwin10.8.0 (64-bit)

locale:
[1] en_CA.UTF-8/en_CA.UTF-8/en_CA.UTF-8/C/en_CA.UTF-8/en_CA.UTF-8

attached base packages:
[1] stats graphics grDevices utils datasets methods base

other attached packages:
[1] Rcpp_0.10.4

关于c++ - Rcpp map /字典/列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17412432/

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