Search code examples
c++matrixc++14diagonal

How to print all the diagonal elements of a 2d vector


I'm looking for a C++ way using vector to get all the diagonals of a (square) matrix, represented as a 2d vector.

matrix = [
[1,2,3,4],
[5,1,2,3],
[9,5,1,2]]

But I have trouble coming up with a way to generate all the diagonals. The output I'm looking for is:

"[9]", "[5, 5]", "[1, 1, 1]", "[2, 2, 2]", "[3, 3]", "[4]".

I found answers but all of them are in python. I need it in C++


Solution

  • The solution is rather straigt forward. I will first show the code and then explain it.

    #include <iostream>
    #include <vector>
    
    using Matrix = std::vector<std::vector<int>>;
    
    int main() {
    
        Matrix matrix{
            {1,2,3,4},
            {5,1,2,3},
            {9,5,1,2}
        };
        // Shortcut for the width and height of the matrix
        const size_t width{ matrix.at(0).size() };
        const size_t height{ matrix.size() };
    
        // Set start row and start column
        size_t startRow{ height-1 };
        size_t startColumn{ 0 };
        size_t column{};
    
        // for all possible start positions
        do {
            // set the row and column values to the start values
            size_t row{ startRow };
            column = startColumn;
    
            //Now go through the diagonal
            do {
                // Show current value
                std::cout << matrix[row][column] << ' ';
    
                // Set next position in the diagonal
                ++row;      // Go one row down
                ++column;   // Go one column to the right
    
              // As long as we do not cross the border
            } while ((row < height) && (column < width));
    
            std::cout << '\n';
    
            // Calculate new start row and start column
            // If possible
            if (startRow > 0) {
                // Go up
                --startRow;
            }
            else {
                // Else go right
                ++startColumn;
            }
        } while (startColumn < width);
    
        return 0;
    }
    

    So, we need to play a little bit with indices.

    The indices for a diagonal are very simple. Simply start at a startPosition,then we increment the row and the column in each step, until we hit the border.

    For the start positions of the diagonal, we will start at the low left border. Then we will keep the column and decrement the row. If the row is 0 then we go to the right, until we hit the border.

    All this can be formulated very easily in C++.