How to create an array in C ++ using new and initialize each element?

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

bool* a = new bool[100000]; 

Using VS 2008.

Thanks!

+6
c ++ arrays initialization new-operator visual-studio-2008
source share
4 answers

In this case, the only value you can set is false with:

 bool* a = new bool[100000](); 

However, I'm not sure why you think you cannot use a loop. They are there for a reason. You should use only the prepared fill or fill_n (depending on taste).


A note using new "raw" as this is a terrible programming practice. Use std::vector<bool> *:

 std::vector<bool> v; v.resize(100000); std::fill(v.begin(), v.end(), true); // or false 

Or:

 std::vector<bool> v; v.reserve(100000); std::fill_n(std::back_inserter(v), 100000, true); // or false 

* Of course, std::vector<bool> happens to break the corresponding container interface, so it doesn't actually store bool . If std::vector<char> used in this problem.

+12
source share

In addition to what GMan said above, I believe that you can specify an initial value for each value in your vector when constructed as follows.

 vector<bool> a (100000, true); 
+14
source share

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

+2
source share

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 
+1
source share

All Articles