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?
我有一个布尔值的矢量。我需要将其元素从第n个设置为第m个到真。有没有使用循环这样做的优雅方法?
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.
编辑:坦克向所有使用vector
3 个解决方案
#1
std::fill
or std::fill_n
in the algorithm
header should do the trick.
算法头中的std :: fill或std :: 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);
#2
Vector of bool. Sends shivers down my spine.
Bool传染媒介。让我的脊椎发抖。
Have you looked at: std::bitset (for fixed size flag sets) boost::dynamic_bitset (for dynamic size flag sets)
你看过:std :: bitset(对于固定大小的标志集)boost :: dynamic_bitset(对于动态大小标志集)
Set the bottom 8 bits in a row:
连续设置最后8位:
#include <bitset>
#include <iostream>
int main()
{
std::bitset<12> flags;
flags |= 0x0FF;
std::cout << flags;
}
#3
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.
不是我所知道的。您可以尝试使用其中一个算法,如std :: for_each,std :: replace或std :: fill来隐藏您循环遍历元素范围的事实,但循环您将是。
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 :: vector,你可能想阅读Herb Sutter在本文中的“bool怎么样”一节。
#1
std::fill
or std::fill_n
in the algorithm
header should do the trick.
算法头中的std :: fill或std :: 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);
#2
Vector of bool. Sends shivers down my spine.
Bool传染媒介。让我的脊椎发抖。
Have you looked at: std::bitset (for fixed size flag sets) boost::dynamic_bitset (for dynamic size flag sets)
你看过:std :: bitset(对于固定大小的标志集)boost :: dynamic_bitset(对于动态大小标志集)
Set the bottom 8 bits in a row:
连续设置最后8位:
#include <bitset>
#include <iostream>
int main()
{
std::bitset<12> flags;
flags |= 0x0FF;
std::cout << flags;
}
#3
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.
不是我所知道的。您可以尝试使用其中一个算法,如std :: for_each,std :: replace或std :: fill来隐藏您循环遍历元素范围的事实,但循环您将是。
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 :: vector,你可能想阅读Herb Sutter在本文中的“bool怎么样”一节。