表的stl容器

stl container for table

本文关键字:容器 stl 表的      更新时间:2023-10-16

表有数据结构吗?比如存储这个:

    Width    Height
1     5        10
2     3        20
3     10       2

我需要的是通过行号和标题来处理一个值,例如(2,"Height")将给出20。
我知道我可以做一个映射数组或2d数组和一个从列名到编号的映射,但有现成的数据结构吗?

没有直接准备,但STL非常棒,您可以随时组合您的方式:

#include <map>
#include <vector>
#include <string>
#include <iostream>
typedef std::map<std::string, int> col_val_map;
typedef std::vector<col_val_map> table;
int main(){
  table t(3);
  std::string col = "Width";
  t[0][col] = 5;
  t[1][col] = 3;
  t[2][col] = 10;
  col = "Height";
  t[0][col] = 10;
  t[1][col] = 20;
  t[2][col] = 2;
  col = "Random";
  t[0][col] = 42;
  t[1][col] = 1337;
  t[2][col] = 0;
  std::cout << "ttWidthttHeigthttRandomn";
  for(int i=1; i <= 3; ++i){
    std::cout << i << "tt" << t[i-1]["Width"]
                   << "tt" << t[i-1]["Height"]
                   << "tt" << t[i-1]["Random"]
                   << "n";
  }
}

输出显示在Ideone上。

或者,正如@DeadMG所说,恰恰相反:

#include <map>
#include <vector>
#include <string>
#include <iostream>
typedef std::vector<int> row_val_array;
typedef std::map<std::string,row_val_array> table;
int main(){
  table t;
  t["Width"].reserve(3);
  t["Width"][0] = 5;
  t["Width"][1] = 3;
  t["Width"][2] = 10;
  t["Height"].reserve(3);
  t["Height"][0] = 10;
  t["Height"][1] = 20;
  t["Height"][2] = 2;
  t["Random"].reserve(3);
  t["Random"][0] = 42;
  t["Random"][1] = 1337;
  t["Random"][2] = 0;      
  std::cout << "ttWidthttHeigthttRandomn";
  for(int i=1; i <= 3; ++i){
    std::cout << i << "tt" << t["Width"][i-1]
                   << "tt" << t["Height"][i-1]
                   << "tt" << t["Random"][i-1]
                   << "n";
  }
}

同样,在Ideone上显示。

您看过Boost::MultiIndex吗?它几乎就像数据库表的内存表示。您可以查询多行、单行等等。非常强大,非常有用,我认为它可以解决您提出的问题。

取自boost网站:

Boost.MultiIndex具有其他功能,如子对象搜索、范围查询和元素的就地更新,即使不需要多索引功能,也可以方便地替换std::set和set::multiset。

在你的情况下,我会看看composite_key。

一个结构数组就可以了,不是吗?

如果您的表是稀疏的(几乎是空的),那么使用std::pair<int, std::string>作为键的单个std::map是一个很好的解决方案。

唯一不平凡的算法是有效地在列上迭代(但可以使用std::map::lower_bound合理地完成)。

恐怕不在C++标准库中。当然,很多人已经实现了这样的东西——你可以在这里和这里看到我自己的简单实现。