stl :: multimap - 我如何获得数据组? [英] stl::multimap - how do i get groups of data?
问题描述
多重映射本质上具有按键排序的数据组。我想要一个方法,通过它我可以访问这些单个组并获取其聚合值。
例如,在 std :: multimap< string,int>
我存储
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}
存储这些值后, multimap并获得每个组的聚合值。问题是没有在STL中定义任何函数来以这种方式访问MultiMaps。我可以使用 lower_bound
, upper_bound
来手动迭代多重映射并合计群组的内容,但我希望可以已经在STL中定义的更好的方法?
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.
推荐答案
pair<Iter, Iter> range = my_multimap.equal_range("Group1");
int total = accumulate(range.first, range.second, 0);
是一种方法。
修改:
如果您不知道您要查找的群组,而是只查看每个群组,则获取下一个群组的范围完成如下:
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 Equal : 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(), Equal<MultimapType::value_type>());
这篇关于stl :: multimap - 我如何获得数据组?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!