如何将 stl 向量中的一系列元素设置为特定值?
我有一个布尔向量。 我需要将其第 n 到 m 个元素设置为 true
。 有没有一种优雅的方法可以在不使用循环的情况下做到这一点?
编辑:向所有指出使用 vector
问题的人致敬。 然而,我一直在寻找一种更通用的解决方案,例如 jalf 给出的解决方案。
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
据我所知并非如此。 您可以尝试使用 std::for_each、std::replace 或 std::fill 等算法之一来隐藏您正在循环遍历元素范围的事实,但您将会循环。
鉴于您说您正在使用布尔向量 - 如果您使用专业化 std::vector 您可能需要阅读 赫伯·萨特 (Herb Sutter) 的这篇文章。
Not to the best of my knowledge. You could try to use one of the algorithms like std::for_each, std::replace or std::fill to hide to fact that you're looping over the element range, but looping you will be.
Given that you said you're using a vector of booleans - if you're using the specialisation std::vector you might want to read the section "what about bool" in this article by Herb Sutter.
布尔向量。
让我脊背发凉。
您是否看过:
std::bitset(用于固定大小的标志集)
boost::dynamic_bitset(用于动态大小标志集)
连续设置底部 8 位:
Vector of bool.
Sends shivers down my spine.
Have you looked at:
std::bitset (for fixed size flag sets)
boost::dynamic_bitset (for dynamic size flag sets)
Set the bottom 8 bits in a row:
algorithm
标头中的std::fill
或std::fill_n
应该可以解决问题。std::fill
orstd::fill_n
in thealgorithm
header should do the trick.