I need a data container for collecting numeric data based on one or multiple keys (like a key built of int and std::string).
For one key, I simply can use unordered_map<std::string, int> respectively unordered_map<std::string, List<int>> if multiple values should be collected.
What about having multiple keys? Other posts suggested me to use std::make_pair<type1, type2> as key, but this only works for 2 keys and looks a little hacky.
Is there any easy-to-use data structure or library allowing keys built of multiple variables and multiple values assigned to it? The values only must be accessible by the keys (I do not need something like boost::multi_index which provides several interfaces to access values). Furthermore the values must not be sorted in the container, however fast access is desired as the values are added/incremented during data processing.
You can use std::tuple for the same. Tuple Comparison works for multiple elements of almost all built in types. for example
typedef tuple<int, int> tx;
tx t1 = make_tuple(1, 1);
tx t2 = make_tuple(1, 2);
if (t1 == t2) {
cout << "EQUAL" << endl;
}
or
typedef tuple<string, string> tx;
tx t1 = make_tuple("AB", "CD");
tx t2 = make_tuple("AB", "CD");
if (t1 == t2) {
cout << "EQUAL" << endl;
}
Use the tuple as the key in you unordered_map
An example of using map could be
map<tx, int> mp;
mp[make_tuple("AB", "CD")] = 100;
mp[make_tuple("EF", "GH")] = 200;
To Update an existing Key, we can use
mp[t1] = 300;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With