简体   繁体   English

将std :: map转换为Rcpp :: List?

[英]converting an std::map to an Rcpp::List?

What would be the correct way of returning an std::map< std::string, double > as an Rcpp::List object? 返回std::map< std::string, double >作为Rcpp::List对象的正确方法是什么? The default wrap() method results in a named vector being returned to R. 默认的wrap()方法导致将命名的向量返回给R。

In the future, include what you have tried in your question. 将来,请包括您在问题中尝试过的内容。 It will be much more beneficial to you when others are able to explain why what you were trying was not working. 当其他人能够解释您尝试的原因为何不起作用时,它将对您更加有益。 Also, R list s (and Rcpp::List s) are much more versatile than std::map s, so I'm not quite sure how you are trying to store the map's data in the list. 而且,R list (和Rcpp::List )比std::map更具通用性,因此我不太确定您是如何尝试在列表中存储地图数据的。 Presumably the map's keys correspond to the list's names; 大概地图的键对应于列表的名称。 and the values to the list's values? 以及列表值的值? Here's one way to do this: 这是执行此操作的一种方法:

#include <Rcpp.h>

// [[Rcpp::export]]
Rcpp::List map_to_list(Rcpp::CharacterVector cv, Rcpp::NumericVector nv) {
  std::map<std::string, double> my_map;

  for (R_xlen_t i = 0; i < cv.size(); i++) {
    my_map.insert(std::make_pair(Rcpp::as<std::string>(cv[i]), nv[i]));
  }

  Rcpp::List my_list(my_map.size());
  Rcpp::CharacterVector list_names(my_map.size());
  std::map<std::string, double>::const_iterator lhs = my_map.begin(), rhs = my_map.end();

  for (R_xlen_t i = 0; lhs != rhs; ++lhs, i++) {
    my_list[i] = lhs->second;
    list_names[i] = lhs->first;
  }

  my_list.attr("names") = list_names;
  return my_list;
}

/*** R

.names <- letters[1:20]
.values <- rnorm(20)

(res <- map_to_list(.names, .values))
#$a
#[1] -0.8596328

#$b
#[1] 0.1300086

#$c
#[1] -0.1439214

#$d
#[1] -1.017546

## etc...

*/ 

Starting with Rcpp::List my_list(my_map.size()); Rcpp::List my_list(my_map.size()); , I'm initializing the return object to the size of the std::map ; ,我正在将返回对象初始化为std::map的大小; and likewise for an Rcpp::CharacterVector which will be used as the return object's names. 同样对于Rcpp::CharacterVector ,它将用作返回对象的名称。 Using a map iterator and an auxiliary index variable, the map's values ( iterator->second ) are assigned to the corresponding position in the list, whereas its keys ( iterator->first ) are assigned to the temporary name vector. 使用map迭代器和辅助索引变量,将映射的值( iterator->second )分配给列表中的相应位置,而将其键( iterator->first )分配给临时名称向量。 Finally, assign this to the resulting list, and return it. 最后,将其分配给结果列表,然后将其返回。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM