Clasificación de vectores 2D en C++ | Conjunto 1 (Por fila y columna)

Un vector 2D es un vector de vectores. En C++, los vectores 2D se utilizan para crear arrays, tablas o cualquier otra estructura de forma dinámica. Básicamente, es una array implementada con la ayuda de vectores. Se crean utilizando el archivo de encabezado <vector> .

El siguiente es un programa para demostrar vectores 2D en C++:

CPP

// C++ code to demonstrate 2D vector
#include <iostream>
#include <vector> // for 2D vector
using namespace std;
 
// Driver Code
int main()
{
    // Initializing 2D vector "vect" with
    // values
    vector<vector<int> > vect{ { 1, 2, 3 },
                               { 4, 5, 6 },
                               { 7, 8, 9 } };
 
    // Displaying the 2D vector
    for (int i = 0; i < vect.size(); i++) {
        for (int j = 0; j < vect[i].size(); j++)
            cout << vect[i][j] << " ";
        cout << endl;
    }
 
    return 0;
}
Producción

1 2 3 
4 5 6 
7 8 9 

Formas de ordenar un vector 2D

Caso 1: Ordenar una fila particular de un vector 2D
 
Este tipo de clasificación organiza una fila seleccionada de un vector 2D en orden ascendente. Esto se logra usando sort() y pasando iteradores de vector 1D como sus argumentos. En sort(), generalmente toma dos parámetros, el primero es el punto de la array/vector desde donde debe comenzar la clasificación y el segundo parámetro es la longitud hasta la que queremos que se ordene la array/vector. Esta función está incluida en el archivo de encabezado <algorithm> .
 

CPP

// C++ code to demonstrate sorting of a
// row of 2D vector
#include <algorithm> // for sort()
#include <iostream>
#include <vector> // for 2D vector
using namespace std;
 
// Driver Code
int main()
{
    // Initializing 2D vector "vect" with
    // values
    vector<vector<int> > vect{ { 3, 5, 1 },
                               { 4, 8, 6 },
                               { 7, 2, 9 } };
    // Number of rows;
    int m = vect.size();
 
    // Number of columns (Assuming all rows
    // are of same size). We can have different
    // sizes though (like Java).
    int n = vect[0].size();
 
    // Displaying the 2D vector before sorting
    cout << "The Matrix before sorting 1st row is:\n";
    for (int i = 0; i < m; i++) {
        for (int j = 0; j < n; j++)
            cout << vect[i][j] << " ";
        cout << endl;
    }
 
    // Use of "sort()" for sorting first row
    sort(vect[0].begin(), vect[0].end());
 
    // Displaying the 2D vector after sorting
    cout << "The Matrix after sorting 1st row is:\n";
    for (int i = 0; i < m; i++) {
        for (int j = 0; j < n; j++)
            cout << vect[i][j] << " ";
        cout << endl;
    }
 
    return 0;
}
Producción

The Matrix before sorting 1st row is:
3 5 1 
4 8 6 
7 2 9 
The Matrix after sorting 1st row is:
1 3 5 
4 8 6 
7 2 9 

Caso 2: ordenar todo el vector 2D en función de una columna en particular

En este tipo de clasificación, el vector 2D se clasifica por completo en función de una columna elegida. Por ejemplo, si la columna elegida es la segunda, la fila con el valor más pequeño en la segunda columna se convierte en la primera fila, el segundo valor más pequeño en la segunda columna se convierte en la segunda fila y así sucesivamente.

{3, 5, 1}, 
{4, 8, 6}, 
{7, 2, 9};

Después de ordenar esta array por la segunda columna, obtenemos

{7, 2, 9} // Row with smallest value in second column 
{3, 5, 1} // Row with smallest value in second column 
{4, 8, 6}

Esto se logra pasando un tercer argumento en sort() como una llamada a la función explícita definida por el usuario.

CPP

// C++ code to demonstrate sorting of a
// 2D vector on basis of a column
#include <algorithm> // for sort()
#include <iostream>
#include <vector> // for 2D vector
using namespace std;
 
// Driver function to sort the 2D vector
// on basis of a particular column
bool sortcol(const vector<int>& v1, const vector<int>& v2)
{
    return v1[1] < v2[1];
}
 
// Driver Code
int main()
{
    // Initializing 2D vector "vect" with
    // values
    vector<vector<int> > vect{ { 3, 5, 1 },
                               { 4, 8, 6 },
                               { 7, 2, 9 } };
 
    // Number of rows;
    int m = vect.size();
 
    // Number of columns (Assuming all rows
    // are of same size). We can have different
    // sizes though (like Java).
    int n = vect[0].size();
 
    // Displaying the 2D vector before sorting
    cout << "The Matrix before sorting is:\n";
    for (int i = 0; i < m; i++) {
        for (int j = 0; j < n; j++)
            cout << vect[i][j] << " ";
        cout << endl;
    }
 
    // Use of "sort()" for sorting on basis
    // of 2nd column
    sort(vect.begin(), vect.end(), sortcol);
 
    // Displaying the 2D vector after sorting
    cout << "The Matrix after sorting is:\n";
    for (int i = 0; i < m; i++) {
        for (int j = 0; j < n; j++)
            cout << vect[i][j] << " ";
        cout << endl;
    }
    return 0;
}
Producción

The Matrix before sorting is:
3 5 1 
4 8 6 
7 2 9 
The Matrix after sorting is:
7 2 9 
3 5 1 
4 8 6 

Debe leer:

Este artículo es una contribución de Manjeet Singh . Si te gusta GeeksforGeeks y te gustaría contribuir, también puedes escribir un artículo usando write.geeksforgeeks.org o enviar tu artículo por correo a review-team@geeksforgeeks.org. Vea su artículo que aparece en la página principal de GeeksforGeeks y ayude a otros Geeks. Escriba comentarios si encuentra algo incorrecto o si desea compartir más información sobre el tema tratado anteriormente.

Publicación traducida automáticamente

Artículo escrito por GeeksforGeeks-1 y traducido por Barcelona Geeks. The original can be accessed here. Licence: CCBY-SA

Deja una respuesta

Tu dirección de correo electrónico no será publicada. Los campos obligatorios están marcados con *