For_each, but to set each element to a value in C ++

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

x = 100;

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

It's simple enough, but I wonder if there is a function in the STL that does the same; something like for_each, but for the purpose.

+5
source share
2 answers

Use std::fill:

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

Note that if you want to initialize a vector with 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 a vector", but if you just create a vector, use the constructor.

+10
source
vect.assign(n, x);

n - amount of elements.

x is the value to fill.

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

+7

All Articles