stl::multimap - how do i get groups of data?(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_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 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 - 如何获取数据组?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:stl::multimap - 如何获取数据组?
基础教程推荐
- 为什么 RegOpenKeyEx() 在 Vista 64 位上返回错误代码 2021-01-01
- CString 到 char* 2021-01-01
- GDB 显示调用堆栈上函数地址的当前编译二进制文 2022-09-05
- 为什么 typeid.name() 使用 GCC 返回奇怪的字符以及如 2022-09-16
- 通过引用传递 C++ 迭代器有什么问题? 2022-01-01
- 为什么派生模板类不能访问基模板类的标识符? 2021-01-01
- 我应该对 C++ 中的成员变量和函数参数使用相同的名称吗? 2021-01-01
- 非静态 const 成员,不能使用默认赋值运算符 2022-10-09
- 初始化列表*参数*评估顺序 2021-01-01
- 如果我为无符号变量分配负值会发生什么? 2022-01-01
