Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to initialize all elements in an array to the same number in C++

Tags:

c++

arrays

g++

I'm trying to initialize an int array with everything set at -1.

I tried the following, but it doesn't work. It only sets the first value at -1.

int directory[100] = {-1}; 

Why doesn't it work right?

like image 281
neuromancer Avatar asked May 23 '10 03:05

neuromancer


People also ask

How do you initialize an array to a number?

To initialize or instantiate an array as we declare it, meaning we assign values as when we create the array, we can use the following shorthand syntax: int[] myArray = {13, 14, 15}; Or, you could generate a stream of values and assign it back to the array: int[] intArray = IntStream.


1 Answers

I'm surprised at all the answers suggesting vector. They aren't even the same thing!

Use std::fill, from <algorithm>:

int directory[100]; std::fill(directory, directory + 100, -1); 

Not concerned with the question directly, but you might want a nice helper function when it comes to arrays:

template <typename T, size_t N> T* end(T (&pX)[N]) {     return pX + N; } 

Giving:

int directory[100]; std::fill(directory, end(directory), -1); 

So you don't need to list the size twice.

like image 53
GManNickG Avatar answered Sep 21 '22 00:09

GManNickG