stl::multimap - 如何获取数据组? [英] stl::multimap - how do i get groups of data?

查看:17
本文介绍了stl::multimap - 如何获取数据组?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Multimap 本质上具有按键排序的数据组.我想要一种方法,通过它我可以访问这些单独的组并获取它们的聚合值.例如,在 std::multimapstring, 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}

存储这些值后,我应该能够迭代这个多重映射并获得每个组"的聚合值.问题是 STL 中没有定义任何函数来以这种方式访问​​ MultiMap.我可以使用 lower_boundupper_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 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>());

这篇关于stl::multimap - 如何获取数据组?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆