函数参数中的 unordered_map [英] unordered_map in a function argument

查看:54
本文介绍了函数参数中的 unordered_map的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

为什么使用 std::unordered_map 作为函数参数编译失败(我该如何解决)?

Why does using std::unordered_map as a function argument fail to compile (and how do I solve it)?

第一个函数将 std::unordered_map 作为函数参数,但编译失败

This first function has the std::unordered_map as a function parameter, but fails to compile

library(Rcpp)

cppFunction(
  code = 'void test( std::unordered_map< std::string, std::string > um ) {

  }'
  , plugins = "cpp11"
  )

虽然在函数体中声明是没问题的

Whereas it's fine when declared in the body of the function

cppFunction(
  code = 'void test(  ) {
    std::unordered_map< std::string, std::string > um;
  }'
  , plugins = "cpp11"
)

<小时>

额外

我已经成功地将它用作函数参数 这里是我的 spatialwidget 库中的内联 函数


Extra

I've used it successfully as a function argument here in an inline function in my spatialwidget library

感谢 Ralf Stubner 的解释.总之,在使 Rcpp 函数可由 R 调用时,必须有对象的等效 R 表示.

Thanks to Ralf Stubner for the explanation. In summary, when making an Rcpp function callable by R, there has to be an equivalent R representation of the objects.

此代码失败,因为 R 中没有等效的 unordered_map

This code fails because there is no equivalent unordered_map in R

// [[Rcpp::export]]
void test( std::unordered_map< std::string, std::string > um ) {

}

这通过,因为它没有被调用/导出到 R

This passes because it's not being called / exported to R

void test( std::unordered_map< std::string, std::string > um ) {

}

推荐答案

你可以使用 std::vectorstd::list 之类的东西作为函数参数并返回可从 R 调用的函数中的值,因为对于在这些 C++ 数据之间转换的 Rcpp::asRcpp::wrap 存在适当的特化R 知道的结构和 SEXP(两个方向).现在 R 没有原生的类似地图的数据类型(尽管可以在某种程度上使用命名列表),这(可能)这就是为什么 Rcpp 没有对 std::unordered_map 进行内置翻译的原因.对于只能从 C++ 调用的函数没有这样的限制,这就是您的额外"示例有效的原因.

You can use things like std::vector and std::list as function parameter and return values in functions that are callable from R because there exist appropriate specializations for Rcpp::as and Rcpp::wrap that convert between these C++ data structures and SEXPs that R knows about (both directions). Now R has no native map-like data type (although one can use named lists to some extend), which is (probably) why Rcpp has no inbuilt translation for std::unordered_map. There is no such limitation for functions that are only callable from C++, which is why your "extra" example works.

原则上你可以自己定义这样的转换函数,c.f.http://gallery.rcpp.org/articles/custom-templated-wrap-and-as-for-seamingless-interfaces/ 和其中的参考资料.但是,您首先必须决定要在 R 端使用哪种类型的数据结构.

In principle you can define such conversion functions yourself, c.f. http://gallery.rcpp.org/articles/custom-templated-wrap-and-as-for-seamingless-interfaces/ and references therein. However, you first would have to decide on what type of data structure you want to use at the R-side.

这篇关于函数参数中的 unordered_map的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆