支持表查找的数据结构
Data structure which supports table lookups
我有一个用例,我必须在c++实现的数据结构中以表的形式存储以下内容,并支持特定的查询集
["Col1", "Col2", "Col3", "Col4", "Col5"]
["V1"、"V2"、"V3","V4"、"Value1")
等Col1, Col2, Col3, Col4, Col5组成一个主键。Col1、2为字符串类型,col2、4、5为整数类型。
数据结构应该支持以下操作:
支持每一行插入操作
给定Col1, Col2, Col3, Col4的值,找到Col5的值
给定Col1, Col2, COl3, Col4更新Col5
我正在考虑实现一个树和支持查找。有没有标准的算法/更简单的方法来解决这个问题?
伪代码/代码将被欣赏。
谢谢。
您可能想创建一个std::map
,前4列作为键,第5列作为值。我已经采取了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具有紧凑的查找语法。当然,std::vector
作为键的缺点是需要类型同质性,而std::tuple
避免了这一点。如果你真的想要更好的一致性,你可以使用std::vector<boost::any>
作为键,它既可以灵活地使用类型,也可以灵活地使用列大小。
- 一种有效的数据结构,用于按 ID 访问和查找加权随机项
- 保持排序的数据结构,允许log N插入时间,并且可以返回我在log N中查找的元素的索引
- 用于添加和查找查询的适当数据结构
- 用于查找元素的数据结构
- C++ 数据结构队列:使用 for 循环查找队列中最大的元素
- 查找索引数据结构,例如`sTD :: vector`(非数组)
- 是否有具有对数时间插入、删除和查找(带距离)的排序数据结构
- 用于在具有更新查询的二维矩阵中查找最大值的最佳数据结构
- 在任意位置进行快速查找和删除的Deque样数据结构
- 最适合查找最小值的数据结构
- C++数据结构以查找多维数组中的相邻值
- 寻找快速初始化和快速查找的数据结构 (O(1))
- 尝试字典上的数据结构以查找押韵的单词
- 用于在数据结构中查找" "之间的字符串的代码
- 用于存储地址的单列列表的数据结构,更好地在C++中查找O(1)
- 最快的数据结构或算法,可快速查找 2 个键
- 什么是提供O(1)查找的C++数据结构
- 用于查找包含数字的非重叠范围的有效数据结构
- 并查找数据结构
- 支持表查找的数据结构