Biblioteca de algoritmos | Algoritmo STL de magos de C++

Para todos aquellos que aspiran a sobresalir en la programación competitiva, solo tener un conocimiento sobre contenedores de STL es de menor utilidad hasta que uno no es consciente de todo lo que STL tiene para ofrecer. 
STL tiene un océano de algoritmos, para todas las funciones de la biblioteca <algoritmo>: Consulte aquí .
Algunos de los algoritmos más utilizados en vectores y más útiles en Programación Competitiva se mencionan a continuación:

Algoritmos de no manipulación

  1. sort (first_iterator, last_iterator) – Para ordenar el vector dado.
  2. reverse(first_iterator, last_iterator) – Para invertir un vector.
  3. *max_element (first_iterator, last_iterator) – Para encontrar el elemento máximo de un vector.
  4. *min_element (first_iterator, last_iterator) – Para encontrar el elemento mínimo de un vector.
  5. acumular (primer_iterador, último_iterador, valor inicial de la suma) – Hace la suma de los elementos del vector

CPP

// A C++ program to demonstrate working of sort(),
// reverse()
#include <algorithm>
#include <iostream>
#include <vector>
#include <numeric> //For accumulate operation
using namespace std;
 
int main()
{
    // Initializing vector with array values
    int arr[] = {10, 20, 5, 23 ,42 , 15};
    int n = sizeof(arr)/sizeof(arr[0]);
    vector<int> vect(arr, arr+n);
 
    cout << "Vector is: ";
    for (int i=0; i<n; i++)
        cout << vect[i] << " ";
 
    // Sorting the Vector in Ascending order
    sort(vect.begin(), vect.end());
 
    cout << "\nVector after sorting is: ";
    for (int i=0; i<n; i++)
       cout << vect[i] << " ";
 
    // Reversing the Vector
    reverse(vect.begin(), vect.end());
 
    cout << "\nVector after reversing is: ";
    for (int i=0; i<n; i++)
        cout << vect[i] << " ";
 
    cout << "\nMaximum element of vector is: ";
    cout << *max_element(vect.begin(), vect.end());
 
    cout << "\nMinimum element of vector is: ";
    cout << *min_element(vect.begin(), vect.end());
 
    // Starting the summation from 0
    cout << "\nThe summation of vector elements is: ";
    cout << accumulate(vect.begin(), vect.end(), 0);
 
    return 0;
}
Producción

Vector is: 10 20 5 23 42 15 
Vector after sorting is: 5 10 15 20 23 42 
Vector after reversing is: 42 23 20 15 10 5 
Maximum element of vector is: 42
Minimum element of vector is: 5
The summation of vector elements is: 115

       6.count(first_iterator, last_iterator,x) – Para contar las ocurrencias de x en el vector.

       7. find(first_iterator, last_iterator, x) : devuelve un iterador a la primera aparición de x en el vector y apunta a la última dirección del vector ((name_of_vector).end()) si el elemento no está presente en el vector.
 

CPP

// C++ program to demonstrate working of count()
// and find()
#include <algorithm>
#include <iostream>
#include <vector>
using namespace std;
 
int main()
{
    // Initializing vector with array values
    int arr[] = {10, 20, 5, 23 ,42, 20, 15};
    int n = sizeof(arr)/sizeof(arr[0]);
    vector<int> vect(arr, arr+n);
 
    cout << "Occurrences of 20 in vector : ";
 
    // Counts the occurrences of 20 from 1st to
    // last element
    cout << count(vect.begin(), vect.end(), 20);
 
    // find() returns iterator to last address if
    // element not present
    find(vect.begin(), vect.end(),5) != vect.end()?
                         cout << "\nElement found":
                     cout << "\nElement not found";
 
    return 0;
}

       8. binary_search (first_iterator, last_iterator, x) – Comprueba si x existe en el vector ordenado o no.

       9. lower_bound(first_iterator, last_iterator, x) – devuelve un iterador que apunta al primer elemento en el rango [primero, último] que tiene un valor no menor que ‘x’.

       10. upper_bound(first_iterator, last_iterator, x) – devuelve un iterador que apunta al primer elemento en el rango [primero, último] que tiene un valor mayor que ‘x’. 

C++

// C++ program to demonstrate working of lower_bound()
// and upper_bound().
#include <algorithm>
#include <iostream>
#include <vector>
using namespace std;
 
int main()
{
    // Initializing vector with array values
    int arr[] = {5, 10, 15, 20, 20, 23, 42, 45};
    int n = sizeof(arr)/sizeof(arr[0]);
    vector<int> vect(arr, arr+n);
 
    // Sort the array to make sure that lower_bound()
    // and upper_bound() work.
    sort(vect.begin(), vect.end());
 
    // Returns the first occurrence of 20
    auto q = lower_bound(vect.begin(), vect.end(), 20);
 
    // Returns the last occurrence of 20
    auto p = upper_bound(vect.begin(), vect.end(), 20);
 
    cout << "The lower bound is at position: ";
    cout << q-vect.begin() << endl;
 
    cout << "The upper bound is at position: ";
    cout << p-vect.begin() << endl;
 
    return 0;
}
Producción

The lower bound is at position: 3
The upper bound is at position: 5

Algunos algoritmos de manipulación

  1. arr.erase (posición a eliminar) : esto borra el elemento seleccionado en el vector y cambia y cambia el tamaño de los elementos del vector en consecuencia.
  2. arr.erase(unique(arr.begin(),arr.end()),arr.end()) – Esto borra las ocurrencias duplicadas en el vector ordenado en una sola línea.

Producción

El vector es: 5 10 15 20 20 23 42 45
El vector después de borrar el elemento: 5 15 20 20 23 42 45
El vector antes de eliminar las ocurrencias duplicadas: 5 15 20 20 23 42 45
El vector después de eliminar los duplicados: 5 15 20 23 42 45 

       3. next_permutation(first_iterator, last_iterator) – Esto modificó el vector a su siguiente permutación.

       4. prev_permutation(first_iterator, last_iterator) – Esto modificó el vector a su permutación anterior. 

CPP

// C++ program to demonstrate working
// of next_permutation()
// and prev_permutation()
#include <algorithm>
#include <iostream>
#include <vector>
using namespace std;
 
int main()
{
    // Initializing vector with array values
    int arr[] = {5, 10, 15, 20, 20, 23, 42, 45};
    int n = sizeof(arr)/sizeof(arr[0]);
    vector<int> vect(arr, arr+n);
 
    cout << "Given Vector is:\n";
    for (int i=0; i<n; i++)
        cout << vect[i] << " ";
 
    // modifies vector to its next permutation order
    next_permutation(vect.begin(), vect.end());
    cout << "\nVector after performing
                   next permutation:\n";
    for (int i=0; i<n; i++)
        cout << vect[i] << " ";
 
    prev_permutation(vect.begin(), vect.end());
    cout << "\nVector after performing prev
                               permutation:\n";
    for (int i=0; i<n; i++)
        cout << vect[i] << " ";
 
    return 0;
}
Producción

Given Vector is:
5 10 15 20 20 23 42 45 
Vector after performing next permutation:
5 10 15 20 20 23 45 42 
Vector after performing prev permutation:
5 10 15 20 20 23 42 45 

         5. distancia (first_iterator,desired_position) : devuelve la distancia de la posición deseada desde el primer iterador. Esta función es muy útil para encontrar el índice. 

CPP

// C++ program to demonstrate working of distance()
#include <algorithm>
#include <iostream>
#include <vector>
using namespace std;
 
int main()
{
    // Initializing vector with array values
    int arr[] = {5, 10, 15, 20, 20, 23, 42, 45};
    int n = sizeof(arr)/sizeof(arr[0]);
    vector<int> vect(arr, arr+n);
 
    // Return distance of first to maximum element
    cout << "Distance between first to max element: ";
    cout << distance(vect.begin(),
                     max_element(vect.begin(), vect.end()));
    return 0;
}
Producción

Distance between first to max element: 7

Más – Artículos STL
Este artículo es una contribución de Manjeet Singh. Si le gusta GeeksforGeeks y le gustaría contribuir, también puede escribir un artículo y enviarlo 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 *