Namespaces
Variants

std::ranges::find_end

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

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


 
제약된 알고리즘
이 메뉴의 모든 이름은 네임스페이스에 속합니다.std::ranges
비수정 시퀀스 연산
수정 시퀀스 연산
분할 연산
정렬 연산
이진 탐색 연산 (정렬된 범위에 대해)
       
       
집합 연산 (정렬된 범위에 대해)
힙 연산
최소/최대 연산
       
       
순열 연산
폴드 연산
수치 연산
(C++23)            
초기화되지 않은 저장소에 대한 연산
반환 타입
 
헤더에 정의됨<algorithm>
호출 시그니처
template< std::forward_iterator I1, std::sentinel_for<I1> S1,
          std::forward_iterator I2, std::sentinel_for<I2> S2,
          class Pred = ranges::equal_to,
          class Proj1 = std::identity, class Proj2 = std::identity >
    requires std::indirectly_comparable<I1, I2, Pred, Proj1, Proj2>
constexpr ranges::subrange<I1>
    find_end( I1 first1, S1 last1, I2 first2, S2 last2,
              Pred pred = {}, Proj1 proj1 = {}, Proj2 proj2 = {} );
(1) (C++20부터)
template< ranges::forward_range R1, ranges::forward_range R2,
          class Pred = ranges::equal_to,
          class Proj1 = std::identity, class Proj2 = std::identity >
    requires std::indirectly_comparable<ranges::iterator_t<R1>,
                                        ranges::iterator_t<R2>,
                                        Pred, Proj1, Proj2>
constexpr ranges::borrowed_subrange_t<R1>
    find_end( R1&& r1, R2&& r2, Pred pred = {},
              Proj1 proj1 = {}, Proj2 proj2 = {} );
(2) (C++20부터)
template< /*execution-policy*/ Ep,
          std::random_access_iterator I1, std::sized_sentinel_for<I1> S1,
          std::random_access_iterator I2, std::sized_sentinel_for<I2> S2,
          class Pred = ranges::equal_to,
          class Proj1 = identity, class Proj2 = identity>
    requires std::indirectly_comparable<I1, I2, Pred, Proj1, Proj2>
ranges::subrange<I1> find_end( Ep&& policy, I1 first1, S1 last1,
                               I2 first2, S2 last2, Pred pred = {},
                               Proj1 proj1 = {}, Proj2 proj2 = {} );
(3) (C++26부터)
template< /*execution-policy*/ Ep,
          /*sized-random-access-range*/ R1,
          /*sized-random-access-range*/ R2,
          class Pred = ranges::equal_to,
          class Proj1 = identity, class Proj2 = identity>
    requires std::indirectly_comparable<ranges::iterator_t<R1>,
                                        ranges::iterator_t<R2>,
                                        Pred, Proj1, Proj2>
ranges::borrowed_subrange_t<R1>
    find_end( Ep&& policy, R1&& r1, R2&& r2, Pred pred = {},
              Proj1 proj1 = {}, Proj2 proj2 = {} );
(4) (C++26부터)

의 정의는 /*execution-policy*/이 페이지를 참조하십시오; /*sized-random-access-range*/의 정의는 이 페이지를 참조하십시오.

소스 범위에서 대상 범위의 마지막 발생을 검색합니다. 요소들은 (proj1와 proj2에 의해 각각 투영됨) 이진 술어 pred를 사용하여 비교됩니다.

1) 소스 범위는 [first1, last1)이고 대상 범위는 [first2, last2)입니다.
2) 소스 범위는 r1이고 대상 범위는 r2입니다.
3,4) (1,2)와 동일하지만 에 따라 policy실행됩니다.

이 페이지에 설명된 함수형 엔티티는 알고리즘 함수 객체 (비공식적으로 niebloid라고 함)입니다. 즉:

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

매개변수

first1, last1 - 소스를 정의하는 반복자-센티널 쌍 범위
first2, last2 - 대상을 정의하는 반복자-센티널 쌍 범위
r1 - 소스 범위
r2 - 대상 범위
pred - (투영된) 요소에 적용할 조건자
proj1 - 소스 범위의 요소에 적용할 투영
proj2 - 대상 범위의 요소에 적용할 투영
policy - 실행 정책을 사용할

반환값

소스 범위에서 대상 범위의 마지막 발생에 해당하는 부분 범위입니다.

대상 범위가 비어 있거나 소스 범위에 나타나지 않으면 빈 범위가 반환됩니다.

복잡도

주어진 N1 로 ranges::distance(first1, last1) 또는 ranges::distance(r1), 그리고 N2 로 ranges::distance(first2, last2) 또는 ranges::distance(r2):

1,2) 최대 N2⋅(N1-N2+1) 회의 pred 와 proj 적용.
3,4) 𝓞(N2⋅(N1-N2+1)) 회의 pred 와 proj 적용.

예외

3,4) 실행 과정 중:
  • 병렬화에 필요한 임시 메모리 자원을 사용할 수 없는 경우, std::bad_alloc이 발생합니다.
  • 알고리즘 인수를 통해 객체에 접근하는 동안 처리되지 않은 예외가 발생하면, 동작은 실행 정책에 의해 결정됩니다 (표준 정책의 경우 std::terminate가 호출됩니다).

참고

반복자 유형이 bidirectional_iterator를 모델링하는 경우, 끝에서 시작 방향으로 검색하여 검색 효율성을 향상시킬 수 있습니다. random_access_iterator를 모델링하면 비교 속도가 향상될 수 있습니다. 그러나 이 모든 것이 최악의 경우 이론적 복잡성을 바꾸지는 않습니다.

가능한 구현

struct find_end_fn
{
    template<std::forward_iterator I1, std::sentinel_for<I1> S1,
             std::forward_iterator I2, std::sentinel_for<I2> S2,
             class Pred = ranges::equal_to,
             class Proj1 = std::identity, class Proj2 = std::identity>
        requires std::indirectly_comparable<I1, I2, Pred, Proj1, Proj2>
    constexpr ranges::subrange<I1>
        operator()(I1 first1, S1 last1, I2 first2, S2 last2, Pred pred = {},
                   Proj1 proj1 = {}, Proj2 proj2 = {}) const
    {
        if (first2 == last2)
        {
            auto last_it = ranges::next(first1, last1);
            return {last_it, last_it};
        }
        auto result = ranges::search(std::move(first1), last1,
                                     first2, last2, pred, proj1, proj2);
        
        if (result.empty())
            return result;
        
        for (;;)
        {
            auto new_result = ranges::search(std::next(result.begin()), last1,
                                             first2, last2, pred, proj1, proj2);
            if (new_result.empty())
                return result;
            else
                result = std::move(new_result);
        }
    }
    
    template<ranges::forward_range R1, ranges::forward_range R2,
             class Pred = ranges::equal_to,
             class Proj1 = std::identity,
             class Proj2 = std::identity>
        requires std::indirectly_comparable<ranges::iterator_t<R1>,
                                            ranges::iterator_t<R2>,
                                            Pred, Proj1, Proj2>
    constexpr ranges::borrowed_subrange_t<R1>
        operator()(R1&& r1, R2&& r2, Pred pred = {},
                   Proj1 proj1 = {}, Proj2 proj2 = {}) const
    {
        return (*this)(ranges::begin(r1),
                       ranges::next(ranges::begin(r1), ranges::end(r1)),
                       ranges::begin(r2),
                       ranges::next(ranges::begin(r2), ranges::end(r2)),
                       std::move(pred), std::move(proj1), std::move(proj2));
    }
};

inline constexpr find_end_fn find_end{};

예제

#include <algorithm>
#include <array>
#include <cctype>
#include <iostream>
#include <ranges>
#include <string_view>

void print(const auto haystack, const auto needle)
{
    const auto pos = std::distance(haystack.begin(), needle.begin());
    std::cout << "In \"";
    for (const auto c : haystack)
        std::cout << c;
    std::cout << "\" found \"";
    for (const auto c : needle)
        std::cout << c;
    std::cout << "\" at position [" << pos << ".." << pos + needle.size() << ")\n"
        << std::string(4 + pos, ' ') << std::string(needle.size(), '^') << '\n';
}

int main()
{
    using namespace std::literals;
    using std::ranges::find_end;
    
    constexpr auto secret{"password password word..."sv};
    constexpr auto wanted{"password"sv};
    
    constexpr auto found1 = find_end(secret.cbegin(), secret.cend(),
                                     wanted.cbegin(), wanted.cend());
    print(secret, found1);
    
    constexpr auto found2 = find_end(secret, "word"sv);
    print(secret, found2);
    
    const auto found3 = find_end(secret, "ORD"sv,
        [](const char x, const char y)
        { // uses a binary predicate
            return std::tolower(x) == std::tolower(y);
        });
    print(secret, found3);
    
    const auto found4 = find_end(secret, "SWORD"sv, {}, {},
        [](char c) { return std::tolower(c); }); // projects the 2nd range
    print(secret, found4);
    
    static_assert(find_end(secret, "PASS"sv).empty()); // => not found
}

출력:

In "password password word..." found "password" at position [9..17)
             ^^^^^^^^
In "password password word..." found "word" at position [18..22)
                      ^^^^
In "password password word..." found "ord" at position [19..22)
                       ^^^
In "password password word..." found "sword" at position [12..17)
                ^^^^^

참고 항목

특정 범위에서 마지막으로 나타나는 요소 시퀀스를 찾습니다
(함수 템플릿)
특정 조건을 만족하는 마지막 요소를 찾습니다
(알고리즘 함수 객체)
특정 조건을 만족하는 첫 번째 요소를 찾습니다
(알고리즘 함수 객체)
요소 집합 중 하나를 검색합니다
(알고리즘 함수 객체)
같거나 주어진 조건을 만족하는 첫 번째 인접한 두 항목을 찾습니다
(알고리즘 함수 객체)
searches for the first occurrence of a range of elements
(알고리즘 함수 객체)
범위에서 요소의 연속 복사본이 처음 나타나는 것을 검색합니다
(알고리즘 함수 객체)