I have an array with 50 elements
int arr[50];
and I want to set all elements to the same value. How can I do that?
Whatever kind of array you are using, if it provides iterators/pointers you can use the std::fill
algorithm from the <algorithm>
header.
// STL-like container:
std::fill(vect.begin(), vect.end(), value);
// C-style array:
std::fill(arr, arr+elementsCount, value);
(where value
is the value you want to assign and elementsCount
is the number of elements to modify)
Not that implementing such a loop by hand would be so difficult...
// Works for indexable containers
for(size_t i = 0; i<elementsCount; ++i)
arr[i]=value;
Use a std::vector
:
std::vector<int> vect(1000, 3); // initialize with 1000 elements set to the value 3.
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