views:

350

answers:

3

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.

+21  A: 

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);
jalf
+2  A: 

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.

Timo Geusch
I realize there is always a loop under the hood. I was looking for a syntactically elegant way to hide it.
Dima
Thanks for the warning about vector<bool>, by the way.
Dima
+4  A: 

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;
}
Martin York
Thanks. I have already realized the folly of using vector<bool>, and I switched to vector<char>. I was actually looking for a more general solution to this.
Dima