迭代器适配器仅迭代映射中的值?
在做了几年 C# 和最近的 Objective C 之后,我刚刚回到 C++。
我之前做过的一件事是为 std::map 推出我自己的迭代器适配器,它将解引用为值部分,而不是键值对。 这是很常见且自然的事情。 C# 通过其 Dictionary 类的 Keys 和 Values 属性提供此功能。 Objective-C 的 NSDictionary 类似地也有 allKeys 和 allValues。
自从我“离开”以来,Boost 获得了 Range 和 ForEach 库,我现在正在广泛使用它们。 我想知道两者之间是否有一些设施可以做同样的事情,但我还没有找到任何东西。
我正在考虑使用 Boost 的迭代器适配器来实现一些东西,但在我走这条路之前,我想我应该在这里问是否有人知道 Boost 中的这样的设施,或者其他地方有现成的设施?
I'm just getting back into C++ after a couple of years of doing a lot of C#, and recently Objective C.
One thing I've done before is to roll my own iterator adapter for std::map that will deref to just the value part, rather than the key-value pair. This is quite a common and natural thing to do. C# provides this facility with its Keys and Values properties of its Dictionary class. Objective-C's NSDictionary, similarly, has allKeys and allValues.
Since I've been "away", Boost has acquired the Range and ForEach libraries, which I am now using extensively. I wondered if between the two there was some facility to do the same, but I haven't been able to find anything.
I'm thinking of knocking something up using Boost's iterator adapters, but before I go down that route I thought I'd ask here if anyone knows of such a facility in Boost, or somewhere else ready made?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
替换之前的答案,以防其他人像我一样发现这个问题。 从 boost 1.43 开始,提供了一些常用的范围适配器。 在这种情况下,您需要 boost::adaptors::map_values。 相关示例:
http://www.boost.org/doc/libs/1_46_0/libs/range/doc/html/range/reference/adaptors/reference/map_values.html#range.reference.adaptors .reference.map_values.map_values_example
Replacing the previous answer, in case anybody else finds this like I did. As of boost 1.43, there are some commonly used range adaptors provided. In this case, you want boost::adaptors::map_values. The relevant example:
http://www.boost.org/doc/libs/1_46_0/libs/range/doc/html/range/reference/adaptors/reference/map_values.html#range.reference.adaptors.reference.map_values.map_values_example
我认为没有任何现成的东西。 您可以使用 boost::make_transform。
I don't think there's anything out of the box. You can use boost::make_transform.
有一个升压范围适配器正是用于此目的。
请参阅http://www.boost .org/doc/libs/1_53_0/libs/range/doc/html/range/reference/adaptors/reference/map_values.html
(此示例抄自那里)
There is a boost range adaptor for exactly this purpose.
See http://www.boost.org/doc/libs/1_53_0/libs/range/doc/html/range/reference/adaptors/reference/map_values.html
(This example cribbed from there)
继续大卫的回答,还有另一种可能性是通过从 boost::transform_iterator 创建派生类来放置 boule。 我在我的项目中使用这个解决方案:
这会导致更清晰的代码:
Continuing David's answer, there's another possibility to put the boile by creating a derived class from boost::transform_iterator. I'm using this solution in my projects:
This leads to even cleaner code: