Is there any way to initialize a multi dimensional array if it is a data member of a class? (Such as in an initializer list) | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 2

Is there any way to initialize a multi dimensional array if it is a data member of a class? (Such as in an initializer list)

Initializing multi dimensional arrays within a class definition

5th May 2017, 5:07 AM
Albert Lugo
Albert Lugo - avatar
9 Answers
+ 2
Yes, you can initialize it that way.
5th May 2017, 5:48 AM
Toky R.
Toky R. - avatar
+ 2
i didnt know you could place an array in a vector like that, and i was told that the second option vector<vector<>> is extremely inefficient because of the ways vectors store data, is that true?
5th May 2017, 5:23 AM
Albert Lugo
Albert Lugo - avatar
+ 2
@Albert Lugo : Yes it is but you can do it if you can't figure out an other way to make your code work. If you're aiming for fast execution (which is not the case when learning) you can try to use pointers.
5th May 2017, 5:28 AM
Toky R.
Toky R. - avatar
+ 1
inside the constructor of the class
5th May 2017, 5:14 AM
MR Programmer
MR Programmer - avatar
+ 1
yes but i mean using this sort of syntax int nums[size][size]={{1,2,3} , {1,2,3}} ; rather than filling the array with a loop
5th May 2017, 5:17 AM
Albert Lugo
Albert Lugo - avatar
+ 1
If I understand correctly whar you're asking, you can declare a multi dimensional array as a member of a class like any other member. You just need to tell their size. ... private: int arr[10][10]; // an array of 10 lines and 10 collumns ... A good advice I could give you is : try to use the functions introduced by c++ like vectors. ... private: vector<int[10]> a1; //an array with dinamic collumn number with 10 lines each vector< vector<int> > a2; //an array with dinamic collumn number which can have their own number of lines ...
5th May 2017, 5:19 AM
Toky R.
Toky R. - avatar
+ 1
to clarify my original question, what if i had a specific data set which i wanted to place into my multidimensional array using initialization rather than manually adding each value to the array one by one. for example : class mArray { private: int multi[3][3]; public: mArray(): multi[ ] [ ] ( {1,2,3} , {1,2,3} ) {} }; would this type of initialization be at all possible?
5th May 2017, 5:38 AM
Albert Lugo
Albert Lugo - avatar
+ 1
thanks for the help buddy!
5th May 2017, 5:48 AM
Albert Lugo
Albert Lugo - avatar
+ 1
no problem ;)
5th May 2017, 5:49 AM
Toky R.
Toky R. - avatar