p-ranav / tabulate

Table Maker for Modern C++

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

How to add a row from a vector?

pthreadself opened this issue · comments

I know that we can do this:
tabulate::Table t; t.add_row({"col1", "col2"});
But how can I add existing data into the table? Say I have a variable named data, whose type is vector and I would like to add it to the table, how do I write the code? The following code won't compile:
t.add_row(data)

add_row takes Row_t, which is a vector<variant>:

using Row_t = std::vector<variant<std::string, const char *, string_view, Table>>;

You have 2 options:

Copy values from data

You can create a Row_t and copy values from data.

#include "tabulate.hpp"
using namespace tabulate;
using Row_t = Table::Row_t;

int main() {

  Table table;

  std::vector<std::string> data{"col1", "col2"};

  Row_t row;
  row.assign(data.begin(), data.end());
  table.add_row(row);

  std::cout << table << std::endl;
}

Move values from data

If you don't want to copy values, you can simply move the values into Row_t

#include "tabulate.hpp"
using namespace tabulate;
using Row_t = Table::Row_t;

int main() {

  Table table;

  std::vector<std::string> data{"col1", "col2"};

  Row_t row;

  // Move values from `data` in to `row`
  row.insert(row.end(),
             std::make_move_iterator(data.begin()),
             std::make_move_iterator(data.end()));

  table.add_row(row);

  std::cout << table << std::endl;
}

Both of above solutions will print:

+------+------+
| col1 | col2 |
+------+------+

@p-ranav Thanks! It would be great if this can be included in the examples.