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

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;


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

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

Leave a Comment