I try to implement the following: I have 3 sets of integers which may not be equal in size. Let's say first has 4 integers, second has 2 integers and last one has 3 integers. How can I store these? I give the integers at initialization and I want to leave the brackets empty! I don't want to use malloc or sth. like that. I tried following and failed:
Try1 and Try2 fails as the 'column' dimensions cant be different in each 'row' .. Not sure, maybe the compiler adds zeros and makes a 3*4 2D array(in this case)
Try3, should definitely not work.
If you want to use a 2D array with different column sizes, use 'vectors'. They are quite easy, and would make your life simple! Plus you can get so many other useful functions with it. http://cplusplus.com/reference/stl/vector/
thanx for replies. In fact I know column sizes can't be different in arrays but I wonder if there is any trick for that... vectors are useful in this case. I'll use them, but if you have anything to say, don't hesitate :)
I'm just fooling around, sorry... My problem is that integer set sizes may change in the future so I just want to give the set and let the compiler do the allocation... I think I don't need vector because during the execution array sizes won't change. If 'new' is capable of allocating memory for a given array (sth like I gave), that would be great but I haven't seen yet. I think there is.
new is dynamic. That means it can allocate on non-constant expressions (where as normal allocation on the stack may not). This also means you can reassign the pointers that control them to other arrays to change size in compile time. (Though why you wouldn't just use a vector is beyond me.) Be sure to delete a dynamic array when finished with it; the data is not automatically removed. Something in the references will tell you how to operate this stuff.
I would like to know if anybody can suggest a shorter easier method to assign default values to a multi-dimensional vector. For example, I need to do so much circus to init a 2D vector:-
1 2 3 4 5 6 7 8 9 10 11 12 13 14
int a[4][3] = {{1,2,3},{7,7,7},{8,8,8},{5,6,7}};
vector< vector<int> > b(3,3);
vector<int> tmp;
int i,j;
for(i=0;i<4;i++)
{
tmp.clear();
for(j=0;j<3;j++)
tmp.push_back(a[i][j]);
b.push_back(tmp);
}
What a painful method to initialize a vector, in comparison to a 2D array!!
Anybody has a better solution to intialize a 2D vector?
Oops.. I am sorry to make a mistake in one of the earlier posts for int *a[3]; usage with new .
You are right to get an error here.
1 2
int *vertices[3];
vertices[0] = cubeVertices;
coz, vertices is a pointer to an int array of size 3!! That means vertices is NOT an array, and so you cannot use vertices with square brackets [].
Or
coz, vertices is a pointer to an int array of size 3!! Since you try here to point to an array of size 6, you get an error.
I am sorry but I never work with array of pointers, so I may be wrong again in the explanation above.