c++ - 支持表查找的数据结构

标签 c++ algorithm database-design data-structures

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

[“Col1”、“Col2”、“Col3”、“Col4”、“Col5”]

[“V1”、“V2”、“V3”、“V4”、“值1”]

等等

Col1、Col2、Col3、Col4、Col5 一起构成主键。另外Col1、2为字符串类型,2、4、5为整数类型。

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

  1. 支持每行的插入操作。

  2. 给定 Col1、Col2、Col3、Col4 的值,求出 Col5 的值

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

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

伪代码/代码将不胜感激。

谢谢。

最佳答案

您可能想要创建一个std::map前 4 列作为键,第五列作为值。我已将列设为混合 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 具有紧凑的查找语法。 OTOH,std::vector 的缺点关键是您需要类型同质性 std::tuple避免。如果你想要真正花哨的内裤,你可以有一个 std::vector<boost::any>作为类型灵活且列大小灵活的键。

关于c++ - 支持表查找的数据结构,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16367752/

相关文章:

c++ - OSX Yosemite 10.10.3 上的 Cmake - GLEW : package 'gl' not found

algorithm - 两个字符串有多少相似?(90%、100%、40%)

javascript - 如何用nodejs打包二维盒子?

mysql - MySQL 中的多对多关系

sql - 如何让一个外键指向两个主键?

c++ - 为什么在 C 或 C++ 中使用 "long long"可能是一件坏事?

c++ - C++中Parents成员变量的继承?

c++ - 从自定义类到内置类型的转换

滑动窗口中的字符串匹配

performance - 数据库速度优化 : few tables with many rows, 或多表少行?