Friday, June 3, 2022
HomeWordPress DevelopmentThe way to move and return a 3-Dimensional Array in C++?

The way to move and return a 3-Dimensional Array in C++?


Enhance Article

Save Article

Like Article

In C++ a three-dimensional array may be applied in two methods:

  • Utilizing array (static)
  • Utilizing vector (dynamic)

Passing a static 3D array in a operate: Utilizing pointers whereas passing the array. Changing it to the equal pointer sort.

char ch[2][2][2];
void show(char (*ch)[2][2]) {
    . . .
}

Program to move a static 3D array as a parameter:

C++

  

#embrace <bits/stdc++.h>

utilizing namespace std;

  

void show(char (*ch)[2][2])

{

    for (int i = 0; i < 2; i++) {

        for (int j = 0; j < 2; j++) {

            for (int ok = 0; ok < 2; ok++) {

                cout << "ch[" << i << "][" << j << "]["

                     << k << "] = " << ch[i][j][k] << endl;

            }

        }

    }

}

  

int principal()

{

    char ch[2][2][2] = { { { 'a', 'b' }, { 'c', 'd' } },

                         { { 'e', 'f' }, { 'g', 'h' } } };

  

    

    show(ch);

    return 0;

}

Output

ch[0][0][0] = a
ch[0][0][1] = b
ch[0][1][0] = c
ch[0][1][1] = d
ch[1][0][0] = e
ch[1][0][1] = f
ch[1][1][0] = g
ch[1][1][1] = h

Passing 3D vector (dynamic array): When a vector is handed to a operate, it may both be handed by worth, the place a duplicate of the vector is saved, or by reference, the place the handle of the vector is handed.

void operate(vector <vector <vector < char >>> ch) {
    . . .
}

  • Cross by reference (Higher):

void operate(vector< vector < vector < char>>> &ch) {
    . . .
}

Program to move a dynamic 3D array as a parameter:

C++

  

#embrace <bits/stdc++.h>

utilizing namespace std;

  

void show(vector<vector<vector<char> > >& ch)

{

    for (int i = 0; i < 2; i++) {

        for (int j = 0; j < 2; j++) {

            for (int ok = 0; ok < 2; ok++) {

                cout << "ch[" << i << "][" << j << "]["

                     << k << "] = " << ch[i][j][k] << endl;

            }

        }

    }

}

  

int principal()

{

    vector<vector<vector<char> > > ch

        = { { { 'a', 'b' }, { 'c', 'd' } },

            { { 'e', 'f' }, { 'g', 'h' } } };

  

    

    show(ch);

    return 0;

}

Output

ch[0][0][0] = a
ch[0][0][1] = b
ch[0][1][0] = c
ch[0][1][1] = d
ch[1][0][0] = e
ch[1][0][1] = f
ch[1][1][0] = g
ch[1][1][1] = h

Returning a 3D array: A static array can’t be returned from a operate in C++. So we have now to move a 3D vector from a operate to get the performance of returning a 3D array.

vector <vector< vector <char>>> enjoyable() {
    vector <vector< vector <char>>> ch;
    . . .
    return ch;
}

RELATED ARTICLES

LEAVE A REPLY

Please enter your comment!
Please enter your name here

- Advertisment -
Google search engine

Most Popular

Recent Comments