1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67
|
#include <iostream>
#include <iomanip>
#include <algorithm>
#include "PrintUtils.h"
display_table_t & display_table_t::begin_row() {
_table.push_back(std::vector<std::string>());
_current_row++;
return *this;
}
void display_table_t::display() {
// Dimensions of tables
const size_t num_rows = _table.size();
const size_t num_cols = ([&] () {
size_t largest = 0;
for (auto & v : _table) {
largest = std::max(largest, v.size());
}
return largest;
})();
// Pad
for (auto & row : _table) {
while (row.size() < num_cols) {
row.emplace_back(" ");
}
}
// Get the largest string for each col
std::vector<size_t> col_sizes(num_cols);
for (size_t j = 0; j < num_cols; ++j) {
size_t largest = 0;
for (size_t i = 0; i < num_rows; ++i) {
largest = std::max(largest, _table[i][j].size());
}
col_sizes[j] = largest;
}
// construct the output
std::stringstream ss;
ss << std::left;
auto insert_hr = [&]() {
for (size_t j = 0; j < num_cols; ++j) {
ss << std::setw(col_sizes[j] + 3)
<< std::setfill('-') << "+";
}
ss << "+" << std::setfill(' ') << std::endl;
};
{
int i = 0, j = 0;
for (auto & row : _table) {
insert_hr();
ss << "| ";
for (auto & col : row) {
ss << std::setw(col_sizes[j])
<< col << " | ";
j++;
}
ss << std::endl;
i++; j = 0;
}
insert_hr();
}
std::cout << ss.str();
}
|