【问题标题】:Iterate over named List in Rcpp遍历 Rcpp 中的命名列表
【发布时间】:2017-06-13 03:14:40
【问题描述】:

我在 R 中有一个命名列表:

l = list(a=1, b=2)

我想在 Rcpp 中使用这个列表,并遍历值和名称。理想情况下,它可能类似于(为简洁起见使用 C++11 格式):

void print_list (List l)
    for (pair < String, int > &p: l)
        cout << p.first << ": " << p.second;

有没有办法做到这一点(即使使用纯 C++)?

【问题讨论】:

    标签: rcpp


    【解决方案1】:

    其中许多用例实际上在单元测试中可见。

    这里我引用tinytest/cpp/Vector.cpp

    获取名称:

    // [[Rcpp::export]]
    CharacterVector integer_names_get( IntegerVector y ){
        return y.names() ;
    }
    

    按名称索引

    // [[Rcpp::export]]
    int integer_names_indexing( IntegerVector y ){
        return y["foo"] ;
    }
    

    这应该足以让您获得要迭代的向量。

    【讨论】:

    • 如果可能,我想避免“按名称索引”步骤。我知道我会阅读整个列表,如果我理解正确,按名称访问每个元素将是浪费时间 (n(n+1)/2 ?)。
    • 您知道您可以按位置(即索引)对每个向量进行迭代吗?
    • 对不起,我没看懂评论(英语不流利)。您的意思是“您知道您可以按位置(即索引)遍历每个向量吗?”你的意思是:for (int i=0; i&lt;l.size();i++) cout &lt;&lt; l.names()[i] &lt;&lt; ": " &lt;&lt; l[i];
    猜你喜欢
    • 2012-05-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-03-01
    • 2011-06-24
    • 1970-01-01
    • 1970-01-01
    • 2016-08-21
    相关资源
    最近更新 更多