r-lib / cpp11

cpp11 helps you to interact with R objects using C++ code.
https://cpp11.r-lib.org/
Other
199 stars 46 forks source link

Is it possible to create an unnamed list? #304

Closed sara-amira-alassam closed 1 month ago

sara-amira-alassam commented 1 year ago

In the documentation you describe how to create a named list:

#include <cpp11.hpp>

[[cpp11::register]]
cpp11::list foo_push() {
  using namespace cpp11::literals;

  cpp11::writable::list x;
  x.push_back({"foo"_nm = 1});

  return x;
}

Is it possible to create an unnamed list? I've tried something like below but it does not work, and I can't find anything in the documentation about this.

#include <cpp11.hpp>

[[cpp11::register]]
cpp11::list foo_push() {
  using namespace cpp11::literals;

  cpp11::writable::list x;
  x.push_back(1);

  return x;
}
pachadotdev commented 1 year ago

@sara-amira-alassam I had the same question!! I ended up using vectors instead, like this

#include <cpp11.hpp>
#include <cpp11/integers.hpp>

using namespace cpp11;

[[cpp11::register]] integers first_10()
{
    writable::integers x(10);

    int I = 10;

    for (int i = 0; i < I; ++i) {
        x[i] = i + 1;
    }

    return x;
}
sara-amira-alassam commented 1 year ago

Hi, thanks for your response but this does not actually help my exact case. I want to output a list of vectors (which can all be different lengths), therefore simply using integers will not work - my example above was a bit over simplified. I'm actually looking for something more like this:

#include <cpp11.hpp>
#include <vector>

[[cpp11::register]]
cpp11::list foo_push() {
  using namespace cpp11::literals;
  // This variable will actually be created dynamically and we will not know in advance the number of elements in each vector
  std::vector<std::vector<int>> var_a {std::vector<int> {1, 2, 3}, std::vector<int> {4, 5, 6, 7}};

  cpp11::writable::list x;
  for (int i = 0; i < var_a.size(); i++) {
    x.push_back(var_a[i]);
  }
  return x;
}

Is there a way to output a list of vectors, without naming each element?

pachadotdev commented 1 year ago

@sara-amira-alassam I still wonder how to obtain that

pachadotdev commented 1 year ago

Ii @sara-amira-alassam I got it ! I am using cpp11 version 0.4.3.9000. Here I wrote a blog post about named and unnamed lists. https://pacha.dev/blog/2023/06/05/cpp11-omp/#cpp11-unnamed-list