┃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.
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.
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.
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.
I suggest a std::vector<Record>
to hold your records.
Use std::map<key, vector_index>
as an index into your records. This will enable you to access records by different search criteria without sorting the vector all the time.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With