支持表查找的数据结构

Data structure which supports table lookups

本文关键字:数据结构 查找 支持      更新时间:2023-10-16

我有一个用例,我必须在c++实现的数据结构中以表的形式存储以下内容,并支持特定的查询集

["Col1", "Col2", "Col3", "Col4", "Col5"]

["V1"、"V2"、"V3","V4"、"Value1")

Col1, Col2, Col3, Col4, Col5组成一个主键。Col1、2为字符串类型,col2、4、5为整数类型。

数据结构应该支持以下操作:

  1. 支持每一行插入操作

  2. 给定Col1, Col2, Col3, Col4的值,找到Col5的值

  3. 给定Col1, Col2, COl3, Col4更新Col5

我正在考虑实现一个树和支持查找。有没有标准的算法/更简单的方法来解决这个问题?

伪代码/代码将被欣赏。

谢谢。

您可能想创建一个std::map,前4列作为键,第5列作为值。我已经采取了std::stringint混合类型的列,但你可以把它推广到任何你喜欢的。

#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>作为键,它既可以灵活地使用类型,也可以灵活地使用列大小。