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.
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);
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;
}
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 .
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.