【发布时间】:2017-01-20 16:19:13
【问题描述】:
数据库通常是这样的
┃Name|Age|..┃
┠────┼───┼──┨
┃John│025│..┃
┃Carl│033│..┃
┃....│...│..┃
在这种情况下,我指的是具有固定列大小和可变大小的未排序行的表,这些行可以通过 id 来寻址。
C++11(或更早版本)中是否有数据结构可以表示这样的数据?
我想了几种方法来欺骗这样的结构,但没有一个是完美的。
1。单独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";
但是,定义一个包含许多列的表需要大量标记,并且通过在每个 std::vector 上调用 push_back 来写入它真的很乏味。
2。 std::vector 的 std::tuple
(在这种情况下std::pair 就足够了)
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 的存在)
这很好,但是从它读取需要大量标记,这一次,当您必须定义要放入值的新变量时。您可以对任何您需要的变量执行 std::tie值,但这变得不可读。第二种方法几乎完美,但在 C++11 中我不想使用隐式枚举。
3。 std::vector 的 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";
这也很不错,但它遇到了与 2.2 相同的问题。这也只允许std::string 值。不过,作为交换,它提供了更短更好的语法。
【问题讨论】:
-
std::list<row>其中row是一个类,表示您要存储在每一行中的数据。其实这取决于你的要求。 -
大多数数据库使用经典的B-Tree data structure
-
数据结构与算法相关联。需要谈论您将要对数据库做什么 以确定您应该如何存储它。甚至规模也很重要;具有 10 PB 数据的“数据库”将使用不同于具有 10 KB 数据的结构。哪些操作需要快速?按名称查找?按年龄查询?按名称将一张桌子连接到另一张桌子怎么样?线程是一个问题吗?数据列是硬类型还是软类型?读取和写入有多常见?等等等等。
-
您可能对Boost MultiIndex感兴趣
-
我必须以某种方式将其加载到内存中
标签: c++ c++11 data-structures