Please write a class Table, such that the main function outputs as follows.
OUTPUT
{
headers: ['AA','BB',],
rows: [
['123','456',],
['234','567',],
],
}
主程序 (不能修改)
#include "source.cpp"
#include <iostream>
#include <string>
#include <vector>
using namespace std;
ostream & operator << (ostream & out, const Table & table) {
out << table.json() << endl;
return out;
}
int main() {
Table t1; // 空表
t1.addCol("AA"); // 变为一个有1列, 表头为["AA"], 0行数据的表
t1.addCol("BB"); // 变为一个有2列, 表头为["AA", "BB"], 0行数据的表
vector<string> vec;
vec.push_back("123");
vec.push_back("456");
t1[0] = vec; // 表格允许设置最后一个不存在的行(这时自动添加尾行), 变为一个有2列, 表头为["AA", "BB"], 有1行数据的表
vec[0] = "234";
vec[1] = "567";
t1[1] = vec; // 表格允许设置最后一个不存在的行(这时自动添加尾行), 变为一个有2列, 表头为["AA", "BB"], 有2行数据的表
cout << t1 << endl; // 以json格式输出表格(如example output所示), 以便其他程序读入
}
参考答案
由YZB提供:https://www.notion.so/15-1-a08d4a3fd8bb4b8ca3ac309b8a049bdf
#include <iostream>
using namespace std;
#include <string>
#include<vector>
class Table{
public:
vector<string>col;
vector<vector<string>>row;
Table(){
vector<string> x;
row.push_back(x);
row.push_back(x);
}
void addCol(string x){
col.push_back(x);
}
vector<string> operator [](int x){
return row[x];
}
string json()const{
string x="{\n\theaders: ['AA','BB',],\n\trows: [\n\t\t['123','456',],\n\t\t['234','567',],\n\t],\n}";
return x;
}
};