我应该使用什么数据结构来建模数据库/表? [英] What data structure should I use to model a database/table?
问题描述
┃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.
在C ++ 11(或更早版本)中是否存在可以表示这种数据的数据结构?
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::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";
定义一个包含许多列的表需要很多标记,并通过调用<每个 std :: vector
上的code> push_back 确实很乏味。
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.
(在这种情况下,<< c $ c> std :: pair 就足够了)
(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";
(对不起,如果我在这里弄乱了东西,我已经知道存在 std :: tuple
从昨天开始)
(Sorry, if I messed something up here; I've known about the existence of std::tuple
since yesterday)
这很好,但是需要花很多时间来阅读这次,当您必须定义要放入值的新变量时,只需对所需的任何变量执行 std :: tie
值,但变得不可读。第二种方法几乎是完美的,但是我不希望在C ++ 11中使用隐式枚举。
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.
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";
这也很不错,但是它遇到了与2.2相同的问题。而且,这仅允许 std :: string
值。作为交换,它提供了更短更好的语法。
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 :: vector<记录>
来保存您的记录。
I suggest a std::vector<Record>
to hold your records.
使用 std :: map< key,vector_index>
作为记录中的索引。这样一来,您就可以通过不同的搜索条件访问记录,而无需始终对向量进行排序。
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.
这篇关于我应该使用什么数据结构来建模数据库/表?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!