stl::multimap - 如何获取数据组?
Multimap 本质上具有按键排序的数据组。 我想要一种方法来访问这些单独的组并获取它们的聚合值。 例如,在 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 中已经定义了更好的方法? 任何人都可以提出一个解决方案来说明如何获取上例中一组的汇总值。
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.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(6)
是一种方式。
编辑:
如果您不知道要查找的组,并且只是浏览每个组,则可以像这样获取下一组的范围:
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:
如果您已经知道键,则可以使用 multimap::equal_range 使迭代器到达组的开头和结尾; 使用任何标准算法从范围中获得所需的结果。 如果您不知道键,您可以从
begin()
开始并自己迭代它们,比较键以找到每个新组的开头。If you already know the keys, you can use
multimap::equal_range
to get the iterators to the beginning and end of the group; use any standard algorithm to get the desired results from the range. If you don't know the keys, you can start atbegin()
and iterate through them yourself, comparing keys to find the start of each new group.您可以使用可包含每个组的合计总和的备用容器。 要做到这一点,你可以这样做:
当然,如果你有 Lambda(在 C++0x 中),它可能会更简单:
You can use an alternate container that can contain the aggregate sums of each group. To do this you might do something like:
Of course, if you have Lambda's (in C++0x) it could be simpler:
语法:
函数
equal_range()
返回两个迭代器 - 一个迭代器指向包含 key 的第一个元素,另一个迭代器指向包含 key 的最后一个元素之后的点。Syntax:
The function
equal_range()
returns two iterators - one to the first element that contains key, another to a point just after the last element that contains key.不是多地图答案,但如果您愿意,您可以执行以下操作。
Not a multimap answer, but you can do things like the following if you so choose.