C++ Online Compiler
Example: Brute Force Print Sorted Matrix Elements in C++
C
C++
C#
Java
Python
PHP
main.cpp
STDIN
Run
// Brute Force Print Sorted Matrix Elements #include <iostream> #include <vector> #include <algorithm> // For std::sort int main() { // Step 1: Define the matrix std::vector<std::vector<int>> matrix = { {10, 20, 30, 40}, {15, 25, 35, 45}, {27, 29, 37, 48}, {32, 33, 39, 50} }; // Step 2: Create a 1D vector to store all elements std::vector<int> allElements; int R = matrix.size(); int C = matrix[0].size(); // Step 3: Copy all elements from the matrix to the 1D vector for (int i = 0; i < R; ++i) { for (int j = 0; j < C; ++j) { allElements.push_back(matrix[i][j]); } } // Step 4: Sort the 1D vector std::sort(allElements.begin(), allElements.end()); // Step 5: Print the sorted elements std::cout << "Sorted elements (Brute Force):" << std::endl; for (int element : allElements) { std::cout << element << " "; } std::cout << std::endl; return 0; }
Output
Clear
ADVERTISEMENTS