'How do I create an array in C++ using new and initialize each element?

Without iterating through each element, how do I create an array using new and initialize each element to a certain value?

bool* a = new bool[100000];

Using VS 2008.

Thanks!



Solution 1:[1]

In addition to what GMan said above, I believe you can specify an initial value for each value in your vector on construction like this..

vector<bool> a (100000, true);

Solution 2:[2]

You should prefer the vector approach, but you can also use memset.

Solution 3:[3]

If 0 is false and 1 is true considered - you can do

bool* a = new bool[100];
std::fill_n( a, 100, 1 ); // all bool array elements set to true
std::fill_n( a, 100, 0 ); // all bool array elements set to false

Solution 4:[4]

You either get a good book on programming with C or C++ (not both!) where such things are explained in depth, or you never ever use operator new. Please, dear reader, do the world a favour.

If you don't want to learn from books, use at least STL, smart pointers, etc.:

std::vector<bool> bz (100000, false);

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 rchanley
Solution 2 Edward Strange
Solution 3 Mahesh
Solution 4