'Arrays initialization on constructors

I'm trying to convert a program to OOP. The program works with a few arrays:

int tipoBilletes[9] = { 500,300,200,100,50,20,10,1,2 };
int cantBilletes[9] = {0};

So for my conversion, I declared in the header file this:

int *tipoBilletes;
int *cantBilletes;

and in the constructor I wrote

tipoBilletes = new int[9];
cantBilletes = new int[9];

tipoBilletes[0] = 500;
tipoBilletes[1] = 300;
tipoBilletes[2] = 200;
...

It works fine.

My question is, is there any way to initialize it like in Java?

int[] tipoBilletes = new int[]{ 500,300 };

rather than having to set each element one by one?



Solution 1:[1]

No, but you don't necessarily nead to write out each assignment independently. Another option would be:

const int TIPO_BILLETES_COUNT = 9;
const int initialData[TIPO_BILLETES_COUNT] = { 500,200,300,100,50,20,10,1,2 };
std::copy(initialData, initialData + TIPO_BILLETES_COUNT, tipoBilletes);

(Note that you should almost certainly be using a std::vector for this instead of manual dynamic allocation. The initialization is no different with a std::vector though once you've resized it.)

Solution 2:[2]

If you use std::vector you can use boost::assign:

#include <vector>
#include <boost/assign/std/vector.hpp>  
//... 
using namespace boost::assign;
std::vector<int> tipoBilletes;
tipoBilletes += 500, 300, 200, 100, 50, 20, 10, 1, 2;

On the other hand, you should consider using the fixed-size array if it is small and constant size.

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 James McNellis
Solution 2 J. Calleja