std::partición en C++ STL

C++ tiene una clase en su biblioteca de algoritmos STL que nos permite particionar algoritmos fácilmente usando ciertas funciones incorporadas. La partición se refiere al acto de dividir elementos de contenedores dependiendo de una condición dada. 
Operaciones de partición :
1. partición (inicio, fin, condición) : – Esta función se utiliza para dividir los elementos en función de la condición mencionada en sus argumentos.
2. is_partitioned(beg, end, condition) :- Esta función devuelve un valor booleano verdadero si el contenedor está particionado ; de lo contrario, devuelve falso.

CPP

// C++ code to demonstrate the working of
// partition() and is_partitioned()
#include<iostream>
#include<algorithm> // for partition algorithm
#include<vector> // for vector
using namespace std;
int main()
{
    // Initializing vector
    vector<int> vect = { 2, 1, 5, 6, 8, 7 };
     
    // Checking if vector is partitioned
    // using is_partitioned()
    is_partitioned(vect.begin(), vect.end(), [](int x)
    {
        return x%2==0;
         
    })?
     
    cout << "Vector is partitioned":
    cout << "Vector is not partitioned";
    cout << endl;
     
    // partitioning vector using partition()
    partition(vect.begin(), vect.end(), [](int x)
    {
        return x%2==0;
         
    });
     
    // Checking if vector is partitioned
    // using is_partitioned()
    is_partitioned(vect.begin(), vect.end(), [](int x)
    {
        return x%2==0;
         
    })?
     
    cout << "Now, vector is partitioned after partition operation":
    cout << "Vector is still not partitioned after partition operation";
    cout << endl;
     
    // Displaying partitioned Vector
    cout << "The partitioned vector is : ";
    for (int &x : vect) cout << x << " ";
     
    return 0;
     
}

Producción: 

Vector is not partitioned
Now, vector is partitioned after partition operation
The partitioned vector is : 2 8 6 5 1 7

En el código anterior, la función de partición divide el vector dependiendo de si un elemento es par o impar, los elementos pares se dividen de los elementos impares sin ningún orden en particular. 
3. stable_partition(beg, end, condition) :- Esta función se usa para particionar los elementos en base a la condición mencionada en sus argumentos de tal manera que se preserva el orden relativo de los elementos. .
4.partition_point(beg, end, condition) :- Esta función devuelve un iterador que apunta al punto de partición del contenedor, es decir, el primer elemento en el rango particionado [beg, end) para el cual la condición no es verdadera. El contenedor ya debería estar particionado para que esta función funcione.

CPP

// C++ code to demonstrate the working of
// stable_partition() and partition_point()
#include<iostream>
#include<algorithm> // for partition algorithm
#include<vector> // for vector
using namespace std;
int main()
{
    // Initializing vector
    vector<int> vect = { 2, 1, 5, 6, 8, 7 };
     
    // partitioning vector using stable_partition()
    // in sorted order
    stable_partition(vect.begin(), vect.end(), [](int x)
    {
        return x%2 == 0;       
    });
     
    // Displaying partitioned Vector
    cout << "The partitioned vector is : ";
    for (int &x : vect) cout << x << " ";
    cout << endl;
     
    // Declaring iterator
    vector<int>::iterator it1;
     
    // using partition_point() to get ending position of partition
    auto it = partition_point(vect.begin(), vect.end(), [](int x)
    {
        return x%2==0;
    });
     
    // Displaying partitioned Vector
    cout << "The vector elements returning true for condition are : ";
    for ( it1= vect.begin(); it1!=it; it1++)
    cout << *it1 << " ";
    cout << endl;
     
    return 0;
     
}

Producción: 

The partitioned vector is : 2 6 8 1 5 7 
The vector elements returning true for condition are : 2 6 8

En el código anterior, los elementos pares e impares están divididos y en orden creciente (ordenados). Sin embargo, no siempre en orden creciente, aquí los elementos (pares e impares) aparecieron en orden creciente, al igual que el resultado después de la partición. si vect hubiera sido { 2,1,7,8,6,5 } después de stable_partition() sería { 2,8,6,1,7,5 }. Se mantiene el orden de aparición.
5. copia_partición(beg, end, beg1, beg2, condition) :- Esta función copia los elementos particionados en los diferentes contenedores mencionados en sus argumentos. Se necesitan 5 argumentos.Posición inicial y final del contenedor, posición inicial del nuevo contenedor donde se deben copiar los elementos (elementos que devuelven verdadero para la condición), posición inicial del nuevo contenedor donde se deben copiar otros elementos (elementos que devuelven falso para la condición) y la condición . Es necesario cambiar el tamaño de los nuevos contenedores para esta función.

CPP

// C++ code to demonstrate the working of
// partition_copy()
#include<iostream>
#include<algorithm> // for partition algorithm
#include<vector> // for vector
using namespace std;
int main()
{
    // Initializing vector
    vector<int> vect = { 2, 1, 5, 6, 8, 7 };
     
    // Declaring vector1
    vector<int> vect1;
     
    // Declaring vector1
    vector<int> vect2;
     
    // Resizing vectors to suitable size using count_if() and resize()
    int n = count_if (vect.begin(), vect.end(), [](int x)
    {
        return x%2==0;
         
    } );
    vect1.resize(n);
    vect2.resize(vect.size()-n);
     
    // Using partition_copy() to copy partitions
    partition_copy(vect.begin(), vect.end(), vect1.begin(),
                                     vect2.begin(), [](int x)
    {
        return x%2==0;
    });
     
     
    // Displaying partitioned Vector
    cout << "The elements that return true for condition are : ";
    for (int &x : vect1)
            cout << x << " ";
    cout << endl;
     
    // Displaying partitioned Vector
    cout << "The elements that return false for condition are : ";
    for (int &x : vect2)
            cout << x << " ";
    cout << endl;
     
    return 0;   
}

Producción: 

The elements that return true for condition are : 2 6 8 
The elements that return false for condition are : 1 5 7

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 *