Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to set a range of elements in an stl vector to a particular value?

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.

like image 847
Dima Avatar asked Jul 16 '09 16:07

Dima


1 Answers

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); 
like image 197
jalf Avatar answered Sep 23 '22 22:09

jalf