Databases usually look like this
┃Name|Age|..┃ ┠────┼───┼──┨ ┃John│025│..┃ ┃Carl│033│..┃ ┃....│...│..┃ In this case I mean a table with a fixed column size and a variable size of unsorted rows which can be addressed by an id.
Is there a data structure in C++11 (or earlier) that can represent data like this?
I thought of a couple of ways of cheating such a structure, but none of them is perfect.
1. Separate std::vector
std::vector<std::string> name; std::vector<unsigned int> age; // Write name.push_back("John"); age.push_back(25); // Read std::cout << "The first entry is (" << name[0] << " | " << age[0] << ")\n"; Defining a table with many columns takes a lot of markup, though, and writing to it by calling push_back on each std::vector is really tedeous.
2. std::vector of std::tuple
(std::pair would be enough in this case)
std::vector<std::tuple<std::string, unsigned int>> table; // Write table.push_back(std::make_tuple("John", 25)); // Read 1 std::string name; unsigned int age; std::tie(name, age) = table[0]; std::cout << "The first entry is (" << name << " | " << age << ")\n"; // Read 2 enum { NAME = 0, AGE } std::cout << "The first entry is (" << std::get<NAME>(table[0]) << " | " << std::get<AGE>(table[0]) << ")\n"; (Sorry, if I messed something up here; I've known about the existence of std::tuple since yesterday)
This is fine, but reading from it takes a lot of markup, this time, when you have to define new variables that you want to put the values in. You could just do the std::tie to whatever variable you need the values at, but that becomes unreadable. The second method is almost perfect, but using implicit enums is not something I want to do in C++11.
3. std::vector of std::array
enum { NAME = 0, AGE } std::vector<std::array<std::string, 2> table; // Write table.push_back({"John", "25"}); // Read std::cout << "The first entry is (" << table[0][NAME] << " | " << table[0][AGE] << ")\n"; This is also pretty good, but it suffers the same problem as 2.2 did. Also this only allows std::string values. In exchange it offers shorter and nicer syntax, though.
std::list<row>whichrowis a class that represent data that you want to store in each row. Actually it depend on your requirements.