我有一个用例,我必须将以下内容以表的形式存储在用 C++ 实现的数据结构中,并支持某些查询集
[“Col1”、“Col2”、“Col3”、“Col4”、“Col5”]
[“V1”、“V2”、“V3”、“V4”、“值1”]
等等
Col1、Col2、Col3、Col4、Col5 一起构成主键。另外Col1、2为字符串类型,2、4、5为整数类型。
数据结构应支持以下操作:
支持每行的插入操作。
给定 Col1、Col2、Col3、Col4 的值,求出 Col5 的值
给定 Col1、Col2、COl3、Col4 更新 Col5
我正在考虑实现一棵树并支持查找。是否有标准算法/更简单的方法来解决这个问题?
伪代码/代码将不胜感激。
谢谢。
最佳答案
您可能想要创建一个std::map
前 4 列作为键,第五列作为值。我已将列设为混合 std::string
和int
类型,但您可以将其概括为您喜欢的任何内容。
#include <map>
#include <utility>
#include <tuple>
#include <iostream>
#include <string>
typedef std::map< std::tuple<std::string, std::string, int, int>, int> Table;
int main()
{
Table my_table;
std::string a = "Kode", b = "Warrior";
int c = 3, d = 4, e = 5;
// 1. Support insert operations for each row.
my_table.insert(std::make_pair(std::make_tuple(a, b, c, d), e));
// 2. Given the values for Col1, Col2, Col3, Col4 find the value of Col5
auto it = my_table.find(std::make_tuple(a, b, c, d));
std::cout << it->second; // prints e
// 3. Given Col1, Col2, COl3, Col4 update Col5
it->second = 6; // assign some other value
}
Ideone 上的输出。
一个很大的缺点(但这并不符合您的要求):它不支持列插入,因此它不是电子表格的良好模型。您可以尝试使用 std::map< std::vector<std::string>, std::string>
正如@NarutSereewattanawoot 在评论中提到的那样。您可以修改代码来支持这一点,但您需要一些初始化列表机制来使 make_vector 具有紧凑的查找语法。 OTOH,std::vector
的缺点关键是您需要类型同质性 std::tuple
避免。如果你想要真正花哨的内裤,你可以有一个 std::vector<boost::any>
作为类型灵活且列大小灵活的键。
关于c++ - 支持表查找的数据结构,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16367752/