Namespaces
Variants

std::ranges::unique_copy, std::ranges::unique_copy_result

cppreference.net에서
 
 
알고리즘 라이브러리
제한된 알고리즘 및 Ranges 알고리즘 (C++20)
제한된 알고리즘, 예: ranges::copy, ranges::sort, ...
정렬 및 관련 연산
분할 연산
(C++11)    

정렬 연산
이진 검색 연산
(분할된 범위에 대해)
집합 연산 (정렬된 범위에 대해)
병합 연산 (정렬된 범위에 대해)
힙 연산
최소/최대 연산
(C++11)
(C++17)
사전식 비교 연산
순열 연산


 
제한된 알고리즘
이 메뉴의 모든 이름은 namespace std::ranges
에 속합니다. 비수정 시퀀스 연산
수정 시퀀스 연산
분할 연산
정렬 연산
이진 검색 연산 (정렬된 범위에 대해)
       
       
집합 연산 (정렬된 범위에 대해)
힙 연산
최소/최대 연산
       
       
순열 연산
폴드 연산
수치 연산
(C++23)            
초기화되지 않은 저장소에 대한 연산
반환 타입
 
헤더 <algorithm>
에 정의됨
template< std::input_iterator I, std::sentinel_for<I> S, std::weakly_incrementable O,
          class Proj = std::identity,
          std::indirect_equivalence_relation<std::projected<I, Proj>>
              C = ranges::equal_to >
requires std::indirectly_copyable<I, O> && (std::forward_iterator<I> ||
             (std::input_iterator<O> && std::same_as<std::iter_value_t<I>,
                 std::iter_value_t<O>>) || std::indirectly_copyable_storable<I, O>)
constexpr unique_copy_result<I, O>
    unique_copy( I first, S last, O result, C comp = {}, Proj proj = {} );
호출 서명 (1)
template< ranges::input_range R, std::weakly_incrementable O,
          class Proj = std::identity,
          std::indirect_equivalence_relation<std::projected<ranges::iterator_t<R>,
              Proj>> C = ranges::equal_to >
requires std::indirectly_copyable<ranges::iterator_t<R>, O> &&
             (std::forward_iterator<ranges::iterator_t<R>> ||
             (std::input_iterator<O> && std::same_as<ranges::range_value_t<R>,
                 std::iter_value_t<O>>) ||
             std::indirectly_copyable_storable<ranges::iterator_t<R>, O>)
constexpr unique_copy_result<ranges::borrowed_iterator_t<R>, O>
    unique_copy( R&& r, O result, C comp = {}, Proj proj = {} );
(C++20부터) (2)
(C++20부터)
template< class I, class O >
using unique_copy_result = ranges::in_out_result<I, O>;
헬퍼 타입 (3)
(C++20부터)1)[firstlast) 소스 범위 result의 요소들을 연속된 중복 요소가 없도록
에서 시작하는 대상 범위로 복사합니다. 동일한 요소의 각 그룹에서 첫 번째 요소만 복사됩니다.[firstlast) 범위 [resultresult + N)N = ranges::distance(first, last)는 겹치면 안 됩니다.
두 연속 요소 *(i - 1)*istd::invoke(comp, std::invoke(proj, *(i - 1)), std::invoke(proj, *i)) == true인 경우 동등한 것으로 간주됩니다. 여기서 i는 범위 [first + 1last)의 반복자입니다.
2) (1)과 같지만, r을 범위로 사용하며, ranges::begin(r)first로, ranges::end(r)last로 사용하는 것처럼 동작합니다.

이 페이지에 설명된 함수 유사 개체는 알고리즘 함수 객체 (비공식적으로 niebloids라고 함)입니다. 즉:

  • 이들 중 하나를 호출할 때 명시적 템플릿 인수 목록을 지정할 수 없습니다.
  • 이들 중 어떤 것도 인수 종속 조회에 표시되지 않습니다.
  • 이들 중 하나가 함수 호출 연산자의 왼쪽에 있는 이름으로 일반 비한정 조회에 의해 발견되면 인수 종속 조회가 억제됩니다.

매개변수

first, last - 처리할 요소들의 소스 range 를 정의하는 iterator-sentinel 쌍
r - 요소들의 소스 범위
result - 요소들의 대상 범위
comp - 투영된 요소들을 비교하기 위한 이항 predicate
proj - 요소들에 적용할 투영

반환값

{ last, result + N }

복잡도

정확히 N - 1 번의 해당 predicate comp 적용과, 어떤 projection proj 도 최대 두 배 이상 적용되지 않습니다.

가능한 구현

구현체는 libstdc++ MSVC STL (그리고 서드파티 라이브러리: cmcstl2 , NanoRange , 그리고 range-v3 )에서도 확인할 수 있습니다.

struct unique_copy_fn
{
    template<std::input_iterator I, std::sentinel_for<I> S, std::weakly_incrementable O,
             class Proj = std::identity,
             std::indirect_equivalence_relation<std::projected<I,
                 Proj>> C = ranges::equal_to>
    requires std::indirectly_copyable<I, O> && (std::forward_iterator<I> ||
                 (std::input_iterator<O> && std::same_as<std::iter_value_t<I>,
                     std::iter_value_t<O>>) || std::indirectly_copyable_storable<I, O>)
    constexpr ranges::unique_copy_result<I, O>
        operator()(I first, S last, O result, C comp = {}, Proj proj = {}) const
    {
        if (!(first == last))
        {
            std::iter_value_t<I> value = *first;
            *result = value;
            ++result;
            while (!(++first == last))
            {
                auto&& value2 = *first;
                if (!std::invoke(comp, std::invoke(proj, value2),
                        std::invoke(proj, value)))
                {
                    value = std::forward<decltype(value2)>(value2);
                    *result = value;
                    ++result;
                }
            }
        }
        return {std::move(first), std::move(result)};
    }
    template<ranges::input_range R, std::weakly_incrementable O,
             class Proj = std::identity,
             std::indirect_equivalence_relation<std::projected<ranges::iterator_t<R>,
                 Proj>> C = ranges::equal_to>
    requires std::indirectly_copyable<ranges::iterator_t<R>, O> &&
                 (std::forward_iterator<ranges::iterator_t<R>> ||
                 (std::input_iterator<O> && std::same_as<ranges::range_value_t<R>,
                     std::iter_value_t<O>>) ||
                 std::indirectly_copyable_storable<ranges::iterator_t<R>, O>)
    constexpr ranges::unique_copy_result<ranges::borrowed_iterator_t
(설명: HTML 태그와 속성은 그대로 유지되었으며, C++ 관련 용어인 `ranges::borrowed_iterator_t`는 번역되지 않았습니다. 링크 구조와 클래스명이 원본 그대로 보존되었습니다.)<R>, O>
        operator()(R&& r, O result, C comp = {}, Proj proj = {}) const
    {
        return (*this)(ranges::begin(r), ranges::end(r), std::move(result),
                       std::move(comp), std::move(proj));
    }
};
inline constexpr unique_copy_fn unique_copy {};

예제

#include <algorithm>
#include <cmath>
#include <iostream>
#include <iterator>
#include <list>
#include <string>
#include <type_traits>
void print(const auto& rem, const auto& v)
{
    using V = std::remove_cvref_t<decltype(v)>;
    constexpr bool sep{std::is_same_v<typename V::value_type, int>};
    std::cout << rem << std::showpos;
    for (const auto& e : v)
        std::cout << e << (sep ? " " : "");
    std::cout << '\n';
}
int main()
{
    std::string s1{"The      string    with many       spaces!"};
    print("s1: ", s1);
    std::string s2;
    std::ranges::unique_copy(
        s1.begin(), s1.end(), std::back_inserter(s2),
        [](char c1, char c2) { return c1 == ' ' && c2 == ' '; }
    );
    print("s2: ", s2);
    const auto v1 = {-1, +1, +2, -2, -3, +3, -3};
    print("v1: ", v1);
    std::list<int> v2;
    std::ranges::unique_copy(
        v1, std::back_inserter(v2),
        {}, // 기본 비교자 std::ranges::equal_to
        [](int x) { return std::abs(x); } // 프로젝션
    );
    print("v2: ", v2);
}

출력:

s1: The      string    with many       spaces!
s2: The string with many spaces!
v1: -1 +1 +2 -2 -3 +3 -3 
v2: -1 +2 -3

참고 항목

범위에서 연속된 중복 요소를 제거함
(알고리즘 함수 객체)
요소들의 범위를 새로운 위치로 복사함
(알고리즘 함수 객체)
서로 같은 (또는 주어진 조건자를 만족하는) 첫 번째 인접한 두 항목을 찾음
(알고리즘 함수 객체)
연속된 중복이 없는 일부 범위의 요소들을 복사본으로 생성함
(함수 템플릿)