Welcome to collectivesolver - Programming & Software Q&A with code examples. A website with trusted programming answers. All programs are tested and work.

Contact: aviboots(AT)netvision.net.il

Buy a domain name - Register cheap domain names from $0.99 - Namecheap

Scalable Hosting That Grows With You

Secure & Reliable Web Hosting, Free Domain, Free SSL, 1-Click WordPress Install, Expert 24/7 Support

Semrush - keyword research tool

Boost your online presence with premium web hosting and servers

Disclosure: My content contains affiliate links.

39,970 questions

51,912 answers

573 users

How to mirror a matrix horizontally and vertically in C++

1 Answer

0 votes
#include <iostream>
#include <vector>

using std::vector;
using std::cout;

void printMatrix(const vector<vector<int>>& matrix) {
    for (const auto& row : matrix) {
        for (int val : row) {
            cout << val << " ";
        }
        cout << "\n";
    }
    cout << "\n";
}

// Function to mirror the matrix horizontally (top to bottom)
void mirrorHorizontally(vector<vector<int>>& matrix) {
    int size = matrix.size();
    
    for (int i = 0; i < size / 2; i++) {
        std::swap(matrix[i], matrix[size - i - 1]);
    }
}

// Function to mirror the matrix vertically (left to right)
void mirrorVertically(vector<vector<int>>& matrix) {
    int size = matrix.size();
    
    for (int i = 0; i < size; i++) {
        for (int j = 0; j < size / 2; j++) {
            std::swap(matrix[i][j], matrix[i][size - j - 1]);
        }
    }
}

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

    cout << "Original Matrix:\n";
    printMatrix(matrix);

    // Perform horizontal mirroring
    mirrorHorizontally(matrix);
    cout << "Horizontally Mirrored Matrix:\n";
    printMatrix(matrix);

    // Reset the matrix to original
    matrix = {
        {1, 2, 3},
        {4, 5, 6},
        {7, 8, 9}
    };

    // Perform vertical mirroring
    mirrorVertically(matrix);
    cout << "Vertically Mirrored Matrix:\n";
    printMatrix(matrix);
}




/*
run:

Original Matrix:
1 2 3 
4 5 6 
7 8 9 

Horizontally Mirrored Matrix:
7 8 9 
4 5 6 
1 2 3 

Vertically Mirrored Matrix:
3 2 1 
6 5 4 
9 8 7

*/

 



answered Aug 27, 2025 by avibootz
...