transpose matrix c++ vectors

To transpose a matrix in C++ using vectors, you can follow these steps:

  1. Declare the matrix: Start by declaring a 2D vector to represent the matrix. A vector is a dynamic array in C++, and a 2D vector can be thought of as a vector of vectors. Declare the vector with the desired number of rows and columns.

  2. Initialize the matrix: Initialize the matrix by assigning values to each element. You can either hardcode the values or take input from the user.

  3. Transpose the matrix: To transpose the matrix, you need to interchange the rows with columns. Iterate over the matrix and swap the elements at position (i, j) with (j, i), where i is the row index and j is the column index.

  4. Display the transposed matrix: After transposing the matrix, display the resulting transposed matrix to the user. Iterate over the transposed matrix and print each element.

Here's a code example that demonstrates these steps:

#include <iostream>
#include <vector>

using namespace std;

int main() {
    // Step 1: Declare the matrix
    vector<vector<int>> matrix;

    // Step 2: Initialize the matrix
    int rows, columns;
    cout << "Enter the number of rows: ";
    cin >> rows;
    cout << "Enter the number of columns: ";
    cin >> columns;

    matrix.resize(rows, vector<int>(columns));

    cout << "Enter the elements of the matrix:" << endl;
    for (int i = 0; i < rows; i++) {
        for (int j = 0; j < columns; j++) {
            cin >> matrix[i][j];
        }
    }

    // Step 3: Transpose the matrix
    vector<vector<int>> transposedMatrix(columns, vector<int>(rows));

    for (int i = 0; i < rows; i++) {
        for (int j = 0; j < columns; j++) {
            transposedMatrix[j][i] = matrix[i][j];
        }
    }

    // Step 4: Display the transposed matrix
    cout << "Transposed matrix:" << endl;
    for (int i = 0; i < columns; i++) {
        for (int j = 0; j < rows; j++) {
            cout << transposedMatrix[i][j] << " ";
        }
        cout << endl;
    }

    return 0;
}

This code prompts the user to enter the number of rows and columns for the matrix, then takes input for each element. It then transposes the matrix and displays the transposed matrix.