maxtam642
maxtam642

Reputation: 25

how to get 3rd dimension array in 3d array in C++?

int array[3][3][8] = {
    {{3, 4, 5}, {3, 5, 7}, {5, 6, 7}},
    {{1, 3, 5}, {0, 1, 2, 3, 4, 5, 6, 7}, {1, 5, 7}},
    {{1, 2, 3}, {1, 3, 7}, {0, 1, 7}}
};

User inputs x,y coordinate and direction, at that location they can only move in 0-7 direction. However, each location can only move towards certain direction. Therefore I am making this array to see if that direction is in that x, y coordinate’s array. After I get the 3rd dimension array (becomes 1d array), I will see if user input direction is in that array. For example:

 {3,4,5} at 1x1 // then check if direction is in this array

I tried:

 int new_array[8] = array[1][1];

Error: array must be initialized with a brace-enclosed initializer

 int new_array = array[1][1][]; // {3,4,5}

Error: expected primary-expression before ']' token
So I know this syntax isn't valid, are there other ways to achieve such operation? To copy the 3rd dimension array into a new array.

Upvotes: 1

Views: 377

Answers (2)

Ted Lyngmo
Ted Lyngmo

Reputation: 117861

You could use std::copy:

#include <algorithm>
#include <iterator>

//...

    int new_array[8];

    std::copy(std::begin(array[1][1]),
              std::end(array[1][1]),
              new_array);

Done using std::array:

#include <array>

// ...

    std::array<std::array<std::array<int, 8>, 3>, 3> array = {{
        {{
            {3,4,5},
            {3,5,7},
            {5,6,7}
        }},
        {{
            {1,3,5},
            {0,1,2,3,4,5,6,7},
            {1,5,7}
        }},
        {{
            {1,2,3},
            {1,3,7},
            {0,1,7}
        }},
    }};

    std::array<int, 8> new_array = array[1][1];

    // the same result but simpler:

    auto new_array = array[1][1];

Upvotes: 1

there is no way you can get the col or row of an array like that... if you define a primitive array then you have to navigate the cells and asign the values

int main() {
    int test[2][3][2] = {
                            {
                                {1, 2},
                                {3, 4},
                                {5, 6}
                            }, 
                            {
                                {7, 8}, 
                                {9, 10}, 
                                {11, 12}
                            }
                        };
    int z[2]; 
    for (int i = 0; i < 2; ++i) {
        for (int j = 0; j < 3; ++j) {
            for (int k = 0; k < 2; ++k) {
                z[k] = test[i][j][k];
            }
        }
    }

    for (int k = 0; k < 2; ++k)
    {
        cout << "z[" << k << "] = " << z[k] << endl;
    }
    return 0;

Upvotes: 0

Related Questions