Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

A method to assign the same value to all elements in an array

Tags:

c++

arrays

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?

like image 598
Sam LaManna Avatar asked Nov 27 '22 11:11

Sam LaManna


2 Answers

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;
like image 92
Matteo Italia Avatar answered Dec 07 '22 22:12

Matteo Italia


Use a std::vector:

std::vector<int> vect(1000, 3); // initialize with 1000 elements set to the value 3.
like image 33
GWW Avatar answered Dec 07 '22 23:12

GWW