设置 std::map 中的所有值
如何将 std::map 中的所有值设置为相同的值,而不使用循环迭代每个值?
How to set all the values in a std::map
to the same value, without using a loop iterating over each value?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
使用循环是迄今为止最简单的方法。 事实上,这是一句简单的话:[C++17]
不幸的是,C++ 算法对关联容器的支持在 C++20 之前并不是很好。 因此,我们不能直接使用
std::fill
。无论如何,要使用它们(C++20 之前的版本),我们需要编写适配器 - 对于 std::fill 来说,是一个迭代器适配器。 这是一个最低限度可行(但并不真正一致)的实现,以说明这需要付出多少努力。 我不建议按原样使用它。 使用库(例如 Boost.Iterator )以获得更通用的、生产强度的实施。
这样,我们就可以使用 std::fill 了:
Using a loop is by far the simplest method. In fact, it’s a one-liner:[C++17]
Unfortunately C++ algorithm support for associative containers isn’t great pre-C++20. As a consequence, we can’t directly use
std::fill
.To use them anyway (pre-C++20), we need to write adapters — in the case of
std::fill
, an iterator adapter. Here’s a minimally viable (but not really conforming) implementation to illustrate how much effort this is. I do not advise using it as-is. Use a library (such as Boost.Iterator) for a more general, production-strength implementation.With this, we can use
std::fill
:我遇到了同样的问题,但发现 boost::adaptors::values 返回的范围是可变的,因此它可以与 std::fill 等普通算法一起使用。
I encountered the same problem but found that the range returned by boost::adaptors::values is mutable, so it can then be used with normal algorithms such as std::fill.
boost::assign 库有各种巧妙的东西来帮助初始化容器的内容。 我认为这可以用来避免显式地迭代地图。 不幸的是,地图是难以初始化的奇怪野兽,因为键必须是唯一的。 最重要的是,简单的 for 循环可能是初始化映射的最佳方法。 它可能不是超级优雅,但它可以完成工作,并且任何熟悉 STL 的人都可以立即理解。
这篇文章的其余部分描述了我得出上述结论的过程。
boost::assign 使向映射分配少量值变得简单。
或者
在您的情况下,您想用相同的值初始化整个地图,有实用程序重复和重复_fun。
像这样的东西应该适用于多重映射(未经测试的代码片段)
正如 Konrad Rudolph 所指出的,您不能使用相同的精确值初始化映射,因为键必须是唯一的。
这让生活变得更加复杂(有趣?)。 也许是这样的:
现在,这变得如此复杂,我现在认为简单的迭代是正确的方法
The boost::assign library has all sorts of neat stuff to help out initializing the contents of a container. My thought that this could be used to avoid explicitly iterating through the map. Unfortunately, maps are curious beasts difficult to initialize because the keys must be unique. The bottom line is that a simple for loop is probably the best way to initialize a map. It may not be super elegant, but it gets the job done and is immediatly comprehensible by anyone with any acquaintance with the STL.
The rest of this post describes the journey I took to reach the above conclusion.
The boost::assign makes it simple to assign a small number of values to a map.
or
In your case, where you want to initialize the entire map with the same value, there are the utilities repeat and repeat_fun.
Something like this should work with a multimap ( untested code snippet )
As Konrad Rudolph as pointed out, you cannot initialize a map with the same exact value, because the keys must be unique.
This makes life much more complex ( fun? ). Something like this, perhaps:
Now, this is getting so complex, I now think a simple iteration IS the way to go