如何将 stl 向量中的一系列元素设置为特定值?

发布于 2024-07-28 18:01:23 字数 189 浏览 1 评论 0 原文

我有一个布尔向量。 我需要将其第 n 到 m 个元素设置为 true。 有没有一种优雅的方法可以在不使用循环的情况下做到这一点?

编辑:向所有指出使用 vector 问题的人致敬。 然而,我一直在寻找一种更通用的解决方案,例如 jalf 给出的解决方案。

I have a vector of booleans. I need to set its elements from n-th to m-th to true. Is there an elegant way to do this without using a loop?

Edit: Tanks to all those who pointed out the problems with using vector<bool>. However, I was looking for a more general solution, like the one given by jalf.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

还给你自由 2024-08-04 18:01:44

据我所知并非如此。 您可以尝试使用 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.

心作怪 2024-08-04 18:01:40

布尔向量。
让我脊背发凉。

您是否看过:
std::bitset(用于固定大小的标志集)
boost::dynamic_bitset(用于动态大小标志集)

连续设置底部 8 位:

#include <bitset>
#include <iostream>


int main()
{
    std::bitset<12>      flags;
    flags   |= 0x0FF;

    std::cout << flags;
}  

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:

#include <bitset>
#include <iostream>


int main()
{
    std::bitset<12>      flags;
    flags   |= 0x0FF;

    std::cout << flags;
}  
写下不归期 2024-08-04 18:01:37

algorithm 标头中的 std::fillstd::fill_n 应该可以解决问题。

 // set m elements, starting from myvec.begin() + n to true
std::fill_n(myvec.begin() + n, m, true);

// set all elements between myvec.begin() + n and myvec.begin() + n + m to true
std::fill(myvec.begin() + n, myvec.begin() + n + m, true); 

std::fill or std::fill_n in the algorithm header should do the trick.

 // set m elements, starting from myvec.begin() + n to true
std::fill_n(myvec.begin() + n, m, true);

// set all elements between myvec.begin() + n and myvec.begin() + n + m to true
std::fill(myvec.begin() + n, myvec.begin() + n + m, true); 
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文