Espacios de nombres
Variantes
Acciones

std::merge

De cppreference.com
< cpp‎ | algorithm
 
 
Biblioteca de algoritmos
Políticas de ejecución (C++17)
Operaciones de secuencia no modificantes
(C++11)(C++11)(C++11)
(C++17)
Operaciones de secuencia modificantes
Operaciones en almacenamiento no inicializado
Operaciones de partición
Operaciones de ordenación
(C++11)
Operaciones de búsqueda binaria
Operaciones de conjuntos (en rangos ordenados)
Operaciones de pila
(C++11)
Operaciones mínimo/máximo
(C++11)
(C++17)
Permutaciones
Operaciones numéricas
Bibliotecas C
 
Definido en el archivo de encabezado <algorithm>
template< class InputIt1, class InputIt2, class OutputIt >

OutputIt merge( InputIt1 first1, InputIt1 last1,
                InputIt2 first2, InputIt2 last2

                OutputIt d_first );
(1)
template< class InputIt1, class InputIt2, class OutputIt, class Compare>

OutputIt merge( InputIt1 first1, InputIt1 last1,
                InputIt2 first2, InputIt2 last2

                OutputIt d_first, Compare comp );
(2)
Combina dos rangos ordenados [first1, last1) y [first2, last2) en un principio gama ordenados en d_first. La primera versión utiliza operator< para comparar los elementos, la segunda versión utiliza la comparación comp función dada. El orden relativo de los elementos equivalentes se conserva .
Original:
Merges two sorted ranges [first1, last1) and [first2, last2) into one sorted range beginning at d_first. The first version uses operator< to compare the elements, the second version uses the given comparison function comp. The relative order of equivalent elements is preserved.
The text has been machine-translated via Google Translate.
You can help to correct and verify the translation. Click here for instructions.

Contenido

[editar] Parámetros

first1, last1 -
la primera gama de elementos a fusionar
Original:
the first range of elements to merge
The text has been machine-translated via Google Translate.
You can help to correct and verify the translation. Click here for instructions.
first2, last2 -
la segunda gama de elementos que se fusionan
Original:
the second range of elements to merge
The text has been machine-translated via Google Translate.
You can help to correct and verify the translation. Click here for instructions.
d_first -
el comienzo del rango de destino
Original:
the beginning of the destination range
The text has been machine-translated via Google Translate.
You can help to correct and verify the translation. Click here for instructions.
comp - objeto función de comparación (es decir, un objeto que satisface los requerimientos de Compare) que devuelve ​true si el primer argumento es menor que el segundo.

La signatura de la función de comparación deberá ser equivalente a lo siguiente:

 bool cmp(const Type1 &a, const Type2 &b);

Mientras que la signatura no necesita ser const &, la función no debe modificar los objetos que se le pasaron y debe admitir todos los valores de los tipos (posiblemente const) Type1 y Type2 a pesar de la categoría de valor (por consiguiente, no se permite a Type1 & , ni tampoco a Type1 a menos que para Type1 un movimiento sea equivalente a una copia (desde C++11)).
Los tipos Type1 y Type2 deben ser tales que objetos de tipo InputIt1 y InputIt2 pueden ser desreferenciados y luego convertidos implícitamente a Type1 and Type2 respectively. ​

Requisitos de tipo
-
InputIt1 debe reunir los requerimientos de InputIterator.
-
InputIt2 debe reunir los requerimientos de InputIterator.
-
OutputIt debe reunir los requerimientos de OutputIterator.

[editar] Valor de retorno

Un iterador de salida al elemento más allá del último elemento copiado .
Original:
An output iterator to element past the last element copied.
The text has been machine-translated via Google Translate.
You can help to correct and verify the translation. Click here for instructions.

[editar] Complejidad

En la mayoría de las comparaciones std::distance(first1, last1) + std::distance(first2, last2) + 1 .
Original:
At most std::distance(first1, last1) + std::distance(first2, last2) + 1 comparisons.
The text has been machine-translated via Google Translate.
You can help to correct and verify the translation. Click here for instructions.

[editar] Posible implementación

Primera versión
template<class InputIt1, class InputIt2, class OutputIt>
OutputIt merge(InputIt1 first1, InputIt1 last1,
               InputIt2 first2, InputIt2 last2,
               OutputIt d_first)
{
    for (; first1 != last1; ++d_first) {
        if (first2 == last2) {
            return std::copy(first1, last1, d_first);
        }
        if (*first2 < *first1) {
            *d_first = *first2;
            ++first2;
        } else {
            *d_first = *first1;
            ++first1;
        }
    }
    return std::copy(first2, last2, d_first);
}
Segunda versión
template<class InputIt1, class InputIt2,
         class OutputIt, class Compare>
OutputIt merge(InputIt1 first1, InputIt1 last1,
               InputIt2 first2, InputIt2 last2,
               OutputIt d_first, Compare comp)
{
    for (; first1 != last1; ++d_first) {
        if (first2 == last2) {
            return std::copy(first1, last1, d_first);
        }
        if (comp(*first2, *first1)) {
            *d_first = *first2;
            ++first2;
        } else {
            *d_first = *first1;
            ++first1;
        }
    }
    return std::copy(first2, last2, d_first);
}

[editar] Ejemplo

#include <iostream>
#include <iterator>
#include <cstdlib>
#include <algorithm>
#include <vector>
 
int main() 
{
    const std::size_t items = 10;
 
    std::vector<int> v1, v2, dst;
 
    // fill the vectors
    for (std::size_t idx = 0; idx < items; ++idx) {
        v1.push_back(std::rand()%items);
        v2.push_back(std::rand()%items);
    }
 
    // sort
    std::sort(v1.begin(), v1.end());
    std::sort(v2.begin(), v2.end());
 
    // output v1
    std::cout << "v1 : ";
    std::copy(v1.begin(), v1.end(),
              std::ostream_iterator<int>(std::cout, " "));
    std::cout << '\n';
 
    // output v2
    std::cout << "v2 : ";
    std::copy(v2.begin(), v2.end(),
              std::ostream_iterator<int>(std::cout, " "));
    std::cout << '\n';
 
    // merge
    std::merge(v1.begin(), v1.end(),
               v2.begin(), v2.end(),
               std::back_inserter(dst));
 
    // output
    std::cout << "dst: ";
    std::copy(dst.begin(), dst.end(),
             std::ostream_iterator<int>(std::cout, " "));
    std::cout << '\n';
}

Salida:

v1 : 0 0 2 2 3 3 3 6 7 9 
v2 : 1 2 5 5 6 6 6 6 7 9 
dst: 0 0 1 2 2 2 3 3 3 5 5 6 6 6 6 6 7 7 9 9

[editar] Ver también

Fusiona dos rangos ordenados in situ.
(plantilla de función) [editar]
Ordena un intervalo en orden ascendente
Original:
sorts a range into ascending order
The text has been machine-translated via Google Translate.
You can help to correct and verify the translation. Click here for instructions.

(plantilla de función) [editar]
Ordena un intervalo de elementos, mientras que la preservación del orden entre los elementos iguales
Original:
sorts a range of elements while preserving order between equal elements
The text has been machine-translated via Google Translate.
You can help to correct and verify the translation. Click here for instructions.

(plantilla de función) [editar]