Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

stl::multimap - how do i get groups of data?

Tags:

c++

stl

multimap

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.

like image 237
the_Saint Avatar asked Oct 29 '08 18:10

the_Saint


People also ask

How do you access values in a multimap?

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.

Can you sort a multimap?

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).

What is the difference between map and multimap associative containers?

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.


1 Answers

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>()); 
like image 51
Greg Rogers Avatar answered Sep 20 '22 14:09

Greg Rogers