Putting arrays into another array
How do I store a list of arrays into another set of array? I tried this way but it doesn't work.
float data1[5] = {150.0, 203.0, 165.0, 4.0, 36.0};
float data2[5] = {249.0, 255.0, 253.0, 104.0, 2.0};
float allData[2] = {data1, data2};
cout << allData[1][2] << endl; //this should print 253.0 but it h开发者_如何学Cas error
This didn't allow me to compile. I also tried to change it to float *allData[2] = {data1, data2};
and it allowed me to compile but I don't get the result I want.
What have I done wrong in this? Thanks.
You should use vectors (this example is in C++11):
std::vector<float> data1 = {150.0, 203.0, 165.0, 4.0, 36.0};
std::vector<float> data2 = {249.0, 255.0, 253.0, 104.0, 2.0};
std::vector<std::vector<float>> allData = {data1, data2};
std::cout << allData[0][0] << std::endl;
Note: possibly you want to store pointers to vectors in allData to prevent copying the data, but you should always take care with such constructs as this could very quickly lead to dangling pointers. This is also the case for the solution with plain arrays by the way.
Edit, as R. Martinho Fernandes mentioned in comments:
You can change the construct of allData
to:
std::vector<std::vector<float>> allData = {std::move(data1), std::move(data2)};
It's worth to note however that after this operation data1
and data2
will be emtpy as their contents are moved to allData
. If you do not need them anymore this is the version to prefer (no pointers, no copying).
You can't store arrays that already exist into another array because array objects can't be moved. You can either form an array or arrays:
float allData[][5] =
{
{150.0, 203.0, 165.0, 4.0, 36.0},
{249.0, 255.0, 253.0, 104.0, 2.0}
};
Or you can make your second array an array of pointers to the previous array.
float *allData[] = { data1, data2 };
or even:
float (*allData[])[5] = { &data1, &data2 };
For all of the above, the expression allData[1][2]
should yield the float
value 253 (the third element of the second array).
You want a float[2][]
for a multi-dimensional array.
float data1[5] = {150.0, 203.0, 165.0, 4.0, 36.0};
float data2[5] = {249.0, 255.0, 253.0, 104.0, 2.0};
float** allData = new float*[2];
allData[0] = &data1[0];
allData[1] = &data2[0];
cout << allData[1][2] << endl; //prints 253.0
Using float *allData [2]
is the correct way to do what you are looking for. Trying the code out using DevStudio 2010 works for me. What output are you getting and what were you expecting.
I get 253
as the output, were you expecting 253.0
? In which case, you need to specify the output format for floats:
cout.precision (1);
cout.setf (ios::fixed, ios::floatfield);
cout << allData[1][2] << endl; // this prints 253.0
精彩评论