stl::multimap - how do i get groups of data?(stl::multimap - 如何获取数据组?)
问题描述
Multimap 本质上具有按键排序的数据组.我想要一种方法,通过它我可以访问这些单独的组并获取它们的聚合值.例如,在 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}
存储这些值后,我应该能够迭代这个多重映射并获得每个组"的聚合值.问题是 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 - 如何获取数据组?
基础教程推荐
- 管理共享内存应该分配多少内存?(助推) 2022-12-07
- 如何“在 Finder 中显示"或“在资源管理器中显 2021-01-01
- 如何在不破坏 vtbl 的情况下做相当于 memset(this, ...) 的操作? 2022-01-01
- 为什么语句不能出现在命名空间范围内? 2021-01-01
- 在 C++ 中循环遍历所有 Lua 全局变量 2021-01-01
- 从 std::cin 读取密码 2021-01-01
- 使用从字符串中提取的参数调用函数 2022-01-01
- 如何使图像调整大小以在 Qt 中缩放? 2021-01-01
- 为 C/C++ 中的项目的 makefile 生成依赖项 2022-01-01
- Windows Media Foundation 录制音频 2021-01-01