Search code examples
rcpp

Iterate over named List in Rcpp


I have a named list in R:

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

I would like to use this list in Rcpp, and iterate over both the values and the names. Ideally, it could be something like (using C++11 formatting for the sake of concision):

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

Is there a way to do it (even using plain C++)?


Solution

  • Many of these use cases are in fact visible in the unit tests.

    Here I am quoting from tinytest/cpp/Vector.cpp:

    Get names:

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

    Index by name

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

    That should be enough to get you the vector you aim to iterate over.