Multidimensional Arrays and Their Traversal in C++

Topic Overview

Welcome to today's session on "Multidimensional Arrays and Their Traversal in C++". Multidimensional arrays are types of arrays that store arrays at each index instead of single elements. Picture it as an 'apartment building' with floors (the outer array) and apartments on each floor (the inner array). Our goal today is to strengthen your foundational knowledge of these 'apartment buildings' and how to handle them effectively in C++.

Creating Multidimensional Arrays

To construct a multidimensional array in C++, we use vectors inside vectors. Here's an example of a 2-dimensional array:

#include <iostream>
#include <vector>

int main() {
    // Creating a 2D vector
    std::vector<std::vector<int>> array = {{1, 2, 3},
                                           {4, 5, 6},
                                           {7, 8, 9}};

    // Printing the array
    for (int i = 0; i < array.size(); i++) {
        for (int j = 0; j < array[i].size(); j++) {
            std::cout << array[i][j] << " ";
        }
        std::cout << std::endl;
    }
    return 0;
}

In this example, array is a 2-dimensional vector, just like a 3-story 'apartment building,' where every floor is an inner vector.

Indexing in Multidimensional Arrays

All indices in C++ arrays are 0-based. Let's say you want to visit an apartment on the second floor (index 1) and bring a package to the first unit (index 0) in this building. Here's how you can do it:

#include <iostream>
#include <vector>

int main() {
    std::vector<std::vector<int>> array = {{1, 2, 3},
                                           {4, 5, 6},
                                           {7, 8, 9}};

    // Accessing an element
    std::cout << array[1][0] << std::endl;  // Outputs: 4

    return 0;
}

We visited the element 4 in the array by its position. The number 1 inside the first square brackets refers to the second inner vector, and 0 refers to the first element of that vector.

Updating Multidimensional Arrays

Continuing with the apartment-building analogy, suppose the task was to replace the old locker code (the second element in the first array) with a new one. Here's how we can achieve this:

#include <iostream>
#include <vector>

int main() {
    // Defining and initializing array
    std::vector<std::vector<int>> array = {{1, 2, 3},
                                           {4, 5, 6},
                                           {7, 8, 9}};

    // Updating an element
    array[0][1] = 10;
    for (int i = 0; i < array.size(); i++) {
        for (int j = 0; j < array[i].size(); j++) {
            std::cout << array[i][j] << " ";
        }
        std::cout << std::endl;
    }
    return 0;
}
Sign up

Join the 1M+ learners on CodeSignal

Be a part of our community of 1M+ users who develop and demonstrate their skills on CodeSignal