Reputation:
I'd like to build a multimap such that I can have multiple entries associated with a key and where the key is made up two strings. To make things more complicated, I need to have several strings (3+) associated with each key-pair.
Is there a way to do this by defining a class which encompasses both the key-pair as well as the extra values? Then I'd like to be able to iterate over this multimap returning all entries matching a specific key-pair.
Upvotes: 2
Views: 229
Reputation: 32500
Sure, just combind all the strings together into a single "virtual" string made up of a vector of strings that is sorted lexically. This would be encompassed in a key
class that would look something like:
class key
{
private:
std::vector<std::string> key_values;
public:
key();
void add_key(const std:string& key_value);
bool operator==(const key& cmp);
bool operator<(const key& cmp);
};
The basic process is you would use the key::add_key
function to add a key to the internal key_values
vector, and would sort-insert the keys into that vector. Thus the vector would always be sorted lexically. Then for the operator<
function, you would compare all the keys in each vector lexically. The first key
to have a string that is lexically "less-than" the other key
would be sorted as "less-than" that other key. Otherwise it would be greater-than or equal-to the other key
. If a key is neither less-than or greater than another key
, then it would be considered by weak-ordering to be "equal" per the requirements of the STL multimap.
Upvotes: 1
Reputation: 476990
You can try either of these two:
typedef std::pair<std::string, std::string> keypair;
std::multimap<keypair, std::string>; // #1
std::map<keypair, std::vector<std::string>>; // #2
The first solution, using a multimap, means you only have one single container, so it might feel a bit simpler, whereas the second version, a map of vectors, has the advantage that all data pertaining to one key is stored together. Depending on the use case, either may have better performance, so you should try both and profile.
keypair
is a perfectly valid map key, by the way, since it provides an ordering via lexicographic ordering of the two components.
Upvotes: 2