简体   繁体   中英

Assigning a 2D double array using 1D array of strings, each referring to another 1D array of doubles

I have 4 arrays of size 3. Within my code, I generate some values that I put in those arrays. I'd like to save those in an output file.

What is the most elegant and best practice for such implementation? I am using a double array to store them and a for loop to go through the 2D array and save them, but I don't like this method.

I like to put all arr1, arr2, arr3, arr4 in one string array and loop through the array getting the string, which refers to a double array that has the three values. Hope I didn't make that confusing. This is what I did...

double arr1[3], arr2[3], arr3[3], arr4[3];

//Omitted code that generates content of arrays

double coordinates[4][3] = {{arr1[0], arr1[1], arr1[2]},
                            {arr2[0], arr2[1], arr2[2]},
                            {arr3[0], arr3[1], arr3[2]},
                            {arr4[0], arr4[1], arr4[2]}};

for(int i = 0; i<4; i++)
    {
        for(int j = 0; j<3; j++)
        {
        output << coordinates[i][j]; //writing ith character of array in the file
        if(j<2)
            output<<",";//separate coordinates by a comma
        else 
            output<<"\n";
    }
}

Also, how about vectors in such a case? I never used them, so I am not quite familiar with them. Thank you.

std::array is the preferred construct. This is how you can use it:

#include <iostream>
#include <array>
int main()
{
    std::array<int, 3> arr1, arr2, arr3, arr4;
    std::array<std::array<int, 3>, 4> coordinates{{arr1, arr2, arr3, arr4}};
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM