使用给定键的所有多重映射值填充向量
给定一个 multimap M,这是一种使用特定键创建 M 中所有值的向量
的巧妙方法。
例如,给定多重映射,我怎样才能获得映射到值 123 的所有字符串的向量?
答案很简单,从下限->上限循环,但是有没有一种简洁的无循环方法?
Given a multimap<A,B>
M what's a neat way to create a vector<B>
of all values in M with a specific key.
e.g given a multimap how can I get a vector of all strings mapped to the value 123?
An answer is easy, looping from lower->upper bound, but is there a neat loop-free method?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(7)
无论如何,你需要一个循环。所有“无循环”方法只是将循环抽象出来。
You need a loop anyway. All "loop-free" methods just abstract the loop away.
由于您的“无循环”要求,这有点人为。
我更喜欢:
This is a bit contrived because of your 'no loop' requirement.
I prefer:
您可以通过给定两个迭代器来初始化该向量,如下所示:
但这会给您一个成对的向量(即同时具有键和值)。
另一种选择是将 std::copy 与 back_inserter 之类的东西一起使用,这是隐藏循环的另一种方法,但具有与上面相同的缺点。
这会将元素(如果有)附加到向量 foo 中。
为了仅提取值,我想不出任何方法,只能循环结果,因为我不知道仅获取范围之外的值的标准方法。
You could initialise the vector by giving it two iterators, like this:
but that would give you a vector of pairs (ie, with both the key and value).
Another option would be to use
std::copy
with something like a back_inserter, which is another way to hide the loop, but with the same downside as above.This would append the elements (if any) to the vector foo.
For extracting the values only, I can't think of any way but to loop over the results as I'm not aware of a standard way to get only the value out of a range.
只是对这里其他答案的一些补充......
std::mem_fn
(来自
#include
)可以用作变换运算符的简写:并且我们可以使用
vector::resize
和std::distance
一次性为向量分配空间,而不是使用 back_inserter 重复调整其大小。Just some addenda to the other answers here…
std::mem_fn
(from#include <functional>
) can be used as a shorthand for the transform operator:And we can use
vector::resize
andstd::distance
to allocate space for the vector in one go, rather than repeatedly resizing it with back_inserter.要获取匹配元素,我们可以使用
equal_range
。在映射中,每个元素都是一对。在这种情况下,我们不能直接使用STL复制算法将匹配元素复制到向量中,因为我们不是直接复制元素(对),所以我们本质上要执行“映射”操作(使用函数式编程中的映射/过滤器术语),在 C++ 中我们可以使用
transform
算法来实现:输出:
To get the matching elements we can use
equal_range
.In a map, each element is a pair. In this case, we cannot directly use the STL
copy
algorithm to copy the matching elements into a vector since we are not copying the elements (pairs) directly, so we want to essentially perform a "mapping" operation (using the map/filter terminology from functional programming), which in C++ we can do using thetransform
algorithm:Output:
以下是 STL 风格的实现方式:
Here's the way to do it STL style :
让我们使用 lambda
给定:
multimap M
请求:
vector
(M 中具有特定键“a”的所有值。)方法:
系统环境:
代码示例:
Let's go lambda
given:
multimap<A,B> M
requested:
vector<B>
(of all values in M with a specific key 'a'.)method:
System environment:
Code example: