开发者

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;
开发者_C百科

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?


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.)


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.


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

Yes, starting from C++11 there is a way to do this as shown below. Note that this was proposed in p1009r2.

int *tipoBilletes = new int[] { 500,300,200,100,50,20,10,1,2 };

From new expression documentation the above creates an array of type int[9].

Working demo


Note that you could just use std::vector that will do the memory management for you so that you don't have to worry about memory leaks. But the question was not about how to use std::vector.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜