Hello,

As far as I know, the fastest way to initialize an array is to do so using a for loop...

Does anyone know if there is an equally fast or faster method of initializing a c++ array ?

Any insight on this topic is greatly appreciated.

Thanks,

Colin

Try this funciton from <algorithm>

#include<algorithm>

int array[10000];

fill(&array[0], &array[10000], 0);

right on ! thanks

Tries to say thank you, but I am still getting used to using this forum ... Hopefully this comes through as an actual reply

Colin

>>As far as I know, the fastest way to initialize an array is to do so using a for loop...

For simple data types (char, int, etc) the fastest way to initialize an array to all 0s is to use memset(). If you want to initialize it to some other value then use a loop as you posted.

char array[255] = {0}; // initialize when declared

memset(array,0, sizeof(array));

>>Does anyone know if there is an equally fast or faster method of initializing a c++ array ?
There is no difference between a c++ array and a c array. They are the same thing.

Edited 7 Years Ago by Ancient Dragon: n/a

Thanks for the input. This should keep me busy for a little bit.. I am new to programming so anything helps

thanks again,

Colin

And what do you consider "the safer way" ?

First Person, Please do elaborate on the safer way .. I am all ears.

And what do you consider "the safer way" ?

Letting the standard function handle initialization and forget about
using for loops. Or use something like, int A[2] = {1,2} and let the compiler generate any compile time error there may
be.

Edited 7 Years Ago by firstPerson: n/a

I would consider the 'safer' way to be to ditch the array and go with an STL container such as a vector. In fact, a std::vector is often nicknamed a "C++ Array".
They're automatically initialised since they start out empty by default, and resize automatically every time you "push" some data into it

In addition, vectors are easier to use, and easier to learn (Which is reflected in the fact that some of the 'best of breed' C++ beginner books introduce vectors in their opening chapters)

Edited 7 Years Ago by Bench: n/a

I would consider the 'safer' way to be to ditch the array and go with an STL container such as a vector. In fact, a std::vector is often nicknamed a "C++ Array".
They're automatically initialised since they start out empty by default, and resize automatically every time you "push" some data into it

In addition, vectors are easier to use, and easier to learn (Which is reflected in the fact that some of the 'best of breed' C++ beginner books introduce vectors in their opening chapters)

Yea, or that.

This article has been dead for over six months. Start a new discussion instead.