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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With