Pos*_*elf 7 c++ data-structures c++11
?Name|Age|..?
?????????????
?John?025?..?
?Carl?033?..?
?....?...?..?
Run Code Online (Sandbox Code Playgroud)
在这种情况下,我的意思是一个具有固定列大小和可变大小的未排序行的表,可以通过 id 寻址。
C++11(或更早版本)中是否有数据结构可以表示这样的数据?
我想到了几种欺骗这种结构的方法,但没有一种是完美的。
std::vectorstd::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";
Run Code Online (Sandbox Code Playgroud)
然而,定义一个包含多列的表需要大量的标记,并且通过调用push_back每个列来写入它std::vector真的很乏味。
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";
Run Code Online (Sandbox Code Playgroud)
(对不起,如果我在这里搞砸了;我std::tuple从昨天开始就知道存在)
这很好,但是这一次,当您必须定义要放入值的新变量时,从中读取需要大量标记。您可以std::tie对需要值的任何变量执行该操作,但这会变成不可读。第二种方法几乎是完美的,但是使用隐式枚举并不是我想在 C++11 中做的事情。
std::vector的std::arrayenum
{
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";
Run Code Online (Sandbox Code Playgroud)
这也很不错,但它遇到了与 2.2 相同的问题。此外,这只允许std::string值。不过,作为交换,它提供了更短、更好的语法。
您没有考虑的一件事是使用std::vector某种关联数组的 a ,无论是 astd::map还是std::unordered_map。
这将允许您使用数据库列名称检查向量(或其他顺序容器)中的给定项目
item["Name"]
item["Age"]
Run Code Online (Sandbox Code Playgroud)
等等。显然,您必须使用变体或类似的boost::any值来获取该值。
如果您希望使用 C++ 与数据库对话,并且在编译时知道列的类型(正如您从建议中看到的那样),那么可能值得考虑直接从数据库场景生成具有适当结构的代码的方法。这里和这里已经有几个关于这个主题的问题。如果 db 值为空怎么办?
| 归档时间: |
|
| 查看次数: |
5217 次 |
| 最近记录: |