Reputation: 3598
I have a use case where I have to store the following represented in the form of a table in a data structure implemented in C++ and support certain set of queries
[ "Col1", "Col2", "Col3", "Col4", "Col5" ]
[ "V1", "V2", "V3", "V4", "Value1"]
etc
Col1, Col2, Col3, Col4, Col5 together form a primary key. Also Col1, 2 are of string type and 2, 4 and 5 are of integer type.
The data structure should support the following operations:
Support insert operations for each row.
Given the values for Col1, Col2, Col3, Col4 find the value of Col5
Given Col1, Col2, COl3, Col4 update Col5
I'm thinking of implementing a tree and support lookups. Is there a standard algorithms/a simpler way to solve this problem ?
Pseudo code/Code will be appreciated.
Thanks.
Upvotes: 2
Views: 234
Reputation: 70526
You might want to make a std::map
with the first 4 columns as key, and the 5th as value. I've taken columns to be of mixed std::string
and int
type, but you could generalize that to whatever you like.
#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
}
Output on Ideone.
One big drawback (but it wasn't in your requirements): it does not support column insertion, so it's not a good model for a spreadsheet. You could try to use a std::map< std::vector<std::string>, std::string>
for that as mentioned by @NarutSereewattanawoot in the comments. You can modify your code to support that but you need some initializer-list mechanics to get a make_vector to have compact lookup syntax. OTOH, the drawback of a std::vector
as a key is that you need type homogeneity which std::tuple
avoids. If you want to get really fancy pancy, you could have a std::vector<boost::any>
as the key which is both type-flexible and column-size flexible.
Upvotes: 3