表的stl容器
stl container for table
表有数据结构吗?比如存储这个:
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++标准库中。当然,很多人已经实现了这样的东西——你可以在这里和这里看到我自己的简单实现。
相关文章:
- 在STL容器中使用模板类
- 检查函数返回类型是否与STL容器类型值相同
- STL算法函数在多个一维容器上的使用
- 为什么 STL 容器适配器堆栈中的 top 返回常量引用?
- 如果我真的真的想从 STL 容器继承,并且我继承构造函数并删除新运算符,会发生什么?
- 对象 C++ 向量的 STL 容器
- C++ STL:将空容器传递给lower_bound
- 如何在不破坏现有应用程序的情况下更改 API 中 stl 容器的数据类型?
- 在 STL 容器的 STL 容器上调用 clear
- "迭代器"和"const_iterator"不是 STL 容器的必需成员?
- 删除包含包含动态对象的 STL 容器的智能指针
- C++:在子类中扩展静态 STL 容器/映射成员?
- 是否有具有外部元素分配的序列容器(在 STL 中)?
- ostream 运算符<< 为获取 STL 容器而过载,传递 std::string 会破坏它?
- 没有 STL 容器的迭代器
- 为什么某些 STL 容器(堆栈、队列、优先级队列)不支持迭代器?
- 接受任何 STL 容器的函数
- C++ STL 容器中优先级搜索的优雅方法
- 我们如何打印出C++ STL 容器的value_type?
- 关联容器(STL)中的等式求值