Last active
November 4, 2022 01:56
-
-
Save potat-dev/28702cbbca5dcaec25fa73c4d00cb582 to your computer and use it in GitHub Desktop.
Template function to pretty print table in C++
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// template function to print table | |
template <typename T> | |
void ptable(vector<vector<T>> table, int axis_offset = 0, int split = 10, | |
int tab_size = 8, int index_width = 3, bool round_val = false) { | |
int rows = table.size(); | |
int splitted_parts = rows / split + (rows % split != 0); | |
for (int table_n = 0; table_n < splitted_parts; table_n++) { | |
int columns = min(split, (int)rows - table_n * split); | |
cout << setw(index_width + 3) << " | "; | |
for (int i = 0; i < columns; i++) { | |
cout << " " << setw(tab_size) << i + axis_offset + table_n * split; | |
} | |
cout << endl; | |
cout << string(index_width, '-') << "-+-"; | |
cout << string(columns * (tab_size + 1), '-') << endl; | |
for (int row = 0; row < rows; row++) { | |
cout << setw(index_width) << row + axis_offset << " | "; | |
for (int column = 0; column < columns; column++) { | |
int index = table_n * split + column; | |
cout << setw(tab_size); | |
cout << (round_val ? round(table[row][index]) : table[row][index]); | |
} | |
cout << endl; | |
} | |
cout << endl; | |
} | |
} | |
// example output: | |
// | 0 1 2 3 4 5 | |
// ----+------------------------------------------------------------------------- | |
// 0 | 0.0017979 0.002639 0.00423561 0.00769484 0.0151903 0.0311306 | |
// 1 | 0.002639 0.0026309 0.00424525 0.0076668 0.0149739 0.0310413 | |
// 2 | 0.00423561 0.00424525 0.00429366 0.00769452 0.0149907 0.03101 | |
// 3 | 0.00769484 0.0076668 0.00769452 0.00774157 0.0150098 0.0310436 | |
// 4 | 0.0151903 0.0149739 0.0149907 0.0150098 0.0150485 0.0311538 | |
// 5 | 0.0311306 0.0310413 0.03101 0.0310436 0.0311538 0.0313158 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment