Multimap essentially has groups of data sorted by the key. I want a method by which I could access these individual groups and get their aggregate values. For example, in a std::multimap< string, int >
I store
{"Group1", 1}, {"Group1", 2}, {"Group1", 3}, {"Group2", 10}, {"Group2", 11}, {"Group2", 12}
Having stored these values, I should be able to iterate this multimap and get the aggregate values of each "group". Problem is there aren't any functions defined in STL to access MultiMaps in such a way. I could use lower_bound
, upper_bound
to manually iterate the multimap and total the group's contents, but I am hoping there could be better ways already defined in STL ? Can anyone propose a solution as to how I could get the aggregate values for a group in the above example.
We can find all values of a key in Multimap using is member function equal_range(). It accepts the key as an argument and returns a pair of multimap iterator. This returned pair has a range that represents the entries with given key.
You cannot do that. Multimap in C++ STL is ordered and the order cannot/must not be changed (I think at the bottom line it is using a balanced binary tree for the keys I think, not sure though). What you can do is instantiate a new multimap object passing a comparator that fits your needs (research strict weak order).
The map and the multimap are both containers that manage key/value pairs as single components. The essential difference between the two is that in a map the keys must be unique, while a multimap permits duplicate keys.
pair<Iter, Iter> range = my_multimap.equal_range("Group1"); int total = accumulate(range.first, range.second, 0);
Is one way.
Edit:
If you don't know the group you are looking for, and are just going through each group, getting the next group's range can be done like so:
template <typename Pair> struct Less : public std::binary_function<Pair, Pair, bool> { bool operator()(const Pair &x, const Pair &y) const { return x.first < y.first; } }; Iter first = mmap.begin(); Iter last = adjacent_find(first, mmap.end(), Less<MultimapType::value_type>());
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