std::set_intersection — cppreference.com
Материал из cppreference.com
<metanoindex/>
<tbody> </tbody>
| Определено в заголовочном файле |
||
|
|
(1) | |
|
|
(2) | |
Создает отсортированный диапазон начало в d_first, состоящей из элементов, которые встречаются в обоих диапазонах отсортированы [first1, last1) и [first2, last2). Первая версия ожидает, что обе входные диапазоны должны быть отсортированы с operator<, вторая версия ожидает, что они должны быть отсортированы с данной comp функцию сравнения. Если некоторый элемент не найден m раз в [first1, last1) и n раз в [first2, last2), первые элементы std::min(m, n) будут скопированы из первого диапазона в диапазон назначения. Порядок эквивалентных элементов сохраняется. В результате диапазон не должен пересекаться с любым из входных диапазонов.
Оригинал:
Constructs a sorted range beginning at d_first consisting of elements that are found in both sorted ranges [first1, last1) and [first2, last2). The first version expects both input ranges to be sorted with operator<, the second version expects them to be sorted with the given comparison function comp. If some element is found m times in [first1, last1) and n times in [first2, last2), the first std::min(m, n) elements will be copied from the first range to the destination range. The order of equivalent elements is preserved. The resulting range cannot overlap with either of the input ranges.
Текст был переведён автоматически используя Переводчик Google.
Вы можете проверить и исправить перевод. Для инструкций щёлкните сюда.
Параметры
| first1, last1 | — | первый ряд элементов для изучения Оригинал: the first range of elements to examine Текст был переведён автоматически используя Переводчик Google. |
| first2, last2 | — | второй ряд элементов для изучения Оригинал: the second range of elements to examine Текст был переведён автоматически используя Переводчик Google. |
| comp | — | объект функции сравнения (т.е. объект, удовлетворяющий требованиям Compare), который возвращает true, если первый аргумент "меньше", чем второй.
Определение сравнения должно быть эквивалентно:
Использование |
| Требования к типам | ||
-InputIt1 должен соответствовать требованиям InputIterator.
| ||
-InputIt2 должен соответствовать требованиям InputIterator.
| ||
-OutputIt должен соответствовать требованиям OutputIterator.
| ||
Возвращаемое значение
Iterator в конце прошлого построен диапазон.
Оригинал:
Iterator past the end of the constructed range.
Текст был переведён автоматически используя Переводчик Google.
Вы можете проверить и исправить перевод. Для инструкций щёлкните сюда.
Сложность
В большинстве сравнений 2·(N1+N2-1), где N1 = std::distance(first1, last1) и N2 = std::distance(first2, last2).
Оригинал:
At most 2·(N1+N2-1) comparisons, where N1 = std::distance(first1, last1) and N2 = std::distance(first2, last2).
Текст был переведён автоматически используя Переводчик Google.
Вы можете проверить и исправить перевод. Для инструкций щёлкните сюда.
Возможная реализация
| Первый вариант |
|---|
template<class InputIt1, class InputIt2, class OutputIt> OutputIt set_intersection(InputIt1 first1, InputIt1 last1, InputIt2 first2, InputIt2 last2, OutputIt d_first) { while (first1 != last1 && first2 != last2) { if (*first1 < *first2) { ++first1; } else { if (!(*first2 < *first1)) { *d_first++ = *first1++; } ++first2; } } return d_first; } |
| Второй вариант |
template<class InputIt1, class InputIt2, class OutputIt, class Compare> OutputIt set_intersection(InputIt1 first1, InputIt1 last1, InputIt2 first2, InputIt2 last2, OutputIt d_first, Compare comp) { while (first1 != last1 && first2 != last2) { if (comp(*first1, *first2)) { ++first1; } else { if (!comp(*first2, *first1)) { *d_first++ = *first1++; } ++first2; } } return d_first; } |
Пример
#include <iostream> #include <vector> #include <algorithm> #include <iterator> int main() { std::vector<int> v1{1,2,3,4,5,6,7,8}; std::vector<int> v2{ 5, 7, 9,10}; std::sort(v1.begin(), v1.end()); std::sort(v2.begin(), v2.end()); std::vector<int> v_intersection; std::set_intersection(v1.begin(), v1.end(), v2.begin(), v2.end(), std::back_inserter(v_intersection)); for(int n : v_intersection) std::cout << n << ' '; }
Вывод: