Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

for_each but for setting each element to a value in C++

Tags:

c++

foreach

stl

I have the following code to assign a value to all the elements of a vector:

x = 100;

for (int i=0;i<vect.size();i++)
{
    vect[i] = x;
}

It's straightforward enough, but I'm wondering if there is a function in the STL that does the same thing; something like for_each, but for assignment.

like image 588
Vlad the Impala Avatar asked Apr 05 '10 23:04

Vlad the Impala


1 Answers

Use std::fill:

std::fill(vect.begin(), vect.end(), 100);

Note if you want to initialize a vector to have all the same value, you can use the appropriate constructor:

std::vector<int> v(5, 100); // 5 elements set to 100

assign can be used to "reset the vector", but if you're just making the vector, use the constructor.

like image 51
GManNickG Avatar answered Nov 05 '22 11:11

GManNickG