stl container for table
Is there any data structure for a table? like storing this:
Width Height
1 5 10
2 3 20
3 10 2
What I need is to address a value by row number and title, e.g. (2, "Height") will give 20.
I know I can do an array of maps or 2d array and a map as column name to number, but is the开发者_运维问答re a ready data structure for this?Not directly prepared, but the STL is wonderful and you can always combine your way there:
#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 << "\t\tWidth\t\tHeigth\t\tRandom\n";
for(int i=1; i <= 3; ++i){
std::cout << i << "\t\t" << t[i-1]["Width"]
<< "\t\t" << t[i-1]["Height"]
<< "\t\t" << t[i-1]["Random"]
<< "\n";
}
}
With output shown on Ideone.
Or, as @DeadMG says, just the other way around:
#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 << "\t\tWidth\t\tHeigth\t\tRandom\n";
for(int i=1; i <= 3; ++i){
std::cout << i << "\t\t" << t["Width"][i-1]
<< "\t\t" << t["Height"][i-1]
<< "\t\t" << t["Random"][i-1]
<< "\n";
}
}
Again, shown on Ideone.
Have you looked at Boost::MultiIndex yet? It's almost like an in-memory representation of a database table. You can query on several rows, a single row, and such. Very powerful, very useful, and I think it would solve the issue you're asking.
Taken from the boost website:
Boost.MultiIndex features additional functionalities, like subobject searching, range querying and in-place updating of elements, which make it a convenient replacement for std::set and set::multiset even when no multi-indexing capabilities are needed.
In your case, I'd look at the composite_key.
An array of structures will do, won't it?
If your table is sparse (almost empty) then a single std::map
using an std::pair<int, std::string>
as key is a good solution.
The only non-trivial algorithm is iterating over a column efficiently (but can be done reasonably using std::map::lower_bound
).
Not in the C++ Standard Library, I'm afraid. Of course, lots of people have implemented something like this - you can see my own rather simple-minded implementation here and here.
精彩评论