Is there anyway to do this? This is my first time using an array and its 50 elements and i know they will only get bigger.
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;
使用std::vector
:
std::vector<int> vect(1000, 3); // initialize with 1000 elements set to the value 3.
You can use a for
loop if you must use arrays:
int array[50];
for (int i = 0; i < 50; ++i)
array[i] = number; // where "number" is the number you want to set all the elements to
or as a shortcut, use std::fill
int array[50];
std::fill(array, array + 50, number);
If the number you want to set all the elements to is 0
, you can do this shortcut:
int array[50] = { };
Or if you're talking about std::vector
, there is a constructor that takes the initial size of the vector and what to set each element to:
vector<int> v(50, n); // where "n" is the number to set all the elements to.
for(int i=0;i<sizeofarray;i++)
array[i]=valuetoassign
using method
void func_init_array(int arg[], int length) {
for (int n=0; n<length; n++)
arg[n]=notoassign
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.