2

I am trying to initialize array of objects with the same value

class A
{
   A(int a1)
   {
      var1 = a1;
   }

   var1;
}

int main(void)
{
    // I want to initialize all the objects with 5 without using an array 
    A *arr = new A[10](5); // How to use the constructor to do something like this
    return 0;
}

As i want to pass the same value to all the objects, is there a way to avoid using an array. i.e. I want to avoid doing the following:

A *arr = new A[10]{5, 5, 5, 5, 5, 5, 5, 5, 5, 5}
7
  • The easy answer is to use a vector, but I assume that's out of the question for some reason. Commented Sep 3, 2015 at 22:59
  • Since it is an int array, how about a simple memset() call? Commented Sep 3, 2015 at 23:00
  • @chris yes vector is not an option for me for some reason. Commented Sep 3, 2015 at 23:01
  • @REACHUS the int is just for example. The actual array can be pretty large with some other params in constructor so I was trying to see if the unnecessary memory can be avoided. Commented Sep 3, 2015 at 23:02
  • Or std::array which has a fill function? Commented Sep 3, 2015 at 23:04

1 Answer 1

4

Normally we avoid raw pointers, especially when not encapsulated in std::unique_ptr or other automatic (RAII) pointer types.

Your first choice should be std::array if size is known at compile time, or std::vector if you want dynamic size or a very large array.

The second choice, if you insist on managing the memory yourself, is to use std::fill or std::fill_n from <algorithm>.

In this case, std::fill_n is probably cleaner:

A *arr = new A[10];
std::fill_n( &arr[0], 10, A(5) );

Please at least consider automatic pointer management though:

std::unique_ptr<A[]> arr( new A[10] );
std::fill_n( &arr[0], 10, A(5) );
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.