Namespaces
Variants

std::ranges:: find_end

From cppreference.net
Algorithm library
Constrained algorithms and algorithms on ranges (C++20)
Constrained algorithms, e.g. ranges::copy , ranges::sort , ...
Execution policies (C++17)
Non-modifying sequence operations
Batch operations
(C++17)
Search operations
Modifying sequence operations
Copy operations
(C++11)
(C++11)
Swap operations
Transformation operations
Generation operations
Removing operations
Order-changing operations
(until C++17) (C++11)
(C++20) (C++20)
Sampling operations
(C++17)

Sorting and related operations
Partitioning operations
Sorting operations
Binary search operations
(on partitioned ranges)
Set operations (on sorted ranges)
Merge operations (on sorted ranges)
Heap operations
Minimum/maximum operations
Lexicographical comparison operations
Permutation operations
C library
Numeric operations
Operations on uninitialized memory
Constrained algorithms
All names in this menu belong to namespace std::ranges
Non-modifying sequence operations
Modifying sequence operations
Partitioning operations
Sorting operations
Binary search operations (on sorted ranges)
Set operations (on sorted ranges)
Heap operations
Minimum/maximum operations
Permutation operations
Fold operations
Operations on uninitialized storage
Return types
헤더 파일에 정의됨 <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부터)
1) [ first2 , last2 ) 시퀀스의 마지막 발생을 [ first1 , last1 ) 범위에서 검색합니다. 각각 proj1 proj2 로 투영(projection)된 후, 투영된 요소들은 이진 조건자 pred 를 사용하여 비교됩니다.
2) (1) 과 동일하지만, r1 을 첫 번째 소스 범위로, r2 를 두 번째 소스 범위로 사용합니다. 마치 ranges:: begin ( r1 ) first1 으로, ranges:: end ( r1 ) last1 으로, ranges:: begin ( r2 ) first2 로, 그리고 ranges:: end ( r2 ) last2 로 사용하는 것과 같습니다.

이 페이지에서 설명하는 함수형 개체들은 algorithm function objects (일반적으로 niebloids 로 알려진)입니다. 즉:

목차

매개변수

first1, last1 - 검사할 요소들의 범위 를 정의하는 반복자-센티넬 쌍 (일명 haystack )
first2, last2 - 검색할 요소들의 범위 를 정의하는 반복자-센티넬 쌍 (일명 needle )
r1 - 검사할 요소들의 범위 (일명 haystack )
r2 - 검색할 요소들의 범위 (일명 needle )
pred - 요소들을 비교하기 위한 이항 조건자
proj1 - 첫 번째 범위의 요소들에 적용할 투영
proj2 - 두 번째 범위의 요소들에 적용할 투영

반환값

1) ranges:: subrange < I1 > { } 표현식 { i, i + ( i == last1 ? 0 : ranges:: distance ( first2, last2 ) ) } 로 값 초기화된 객체는 범위 [ first1 , last1 ) 내에서 시퀀스 [ first2 , last2 ) 의 마지막 발생 위치를 나타냅니다(투영자 proj1 proj2 적용 후). [ first2 , last2 ) 가 비어있거나 해당 시퀀스를 찾을 수 없는 경우, 반환값은 실질적으로 { last1, last1 } 로 초기화됩니다.
2) (1) 과 동일하지만, 반환 타입이 ranges:: borrowed_subrange_t < R1 > 입니다.

복잡도

최대 S·(N-S+1) 회의 해당 predicate 및 각 projection이 적용되며, 여기서 S ranges:: distance ( first2, last2 ) 이고 N ranges:: distance ( first1, last1 ) 입니다 (1) 의 경우, 또는 S ranges:: distance ( r2 ) 이고 N ranges:: distance ( r1 ) 입니다 (2) 의 경우.

참고 사항

구현체는 입력 반복자가 std:: bidirectional_iterator 를 모델링하는 경우 끝에서 시작 방향으로 검색하여 효율성을 향상시킬 수 있습니다. std:: 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::end(r1),
                       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;
    constexpr auto secret{"password password word..."sv};
    constexpr auto wanted{"password"sv};
    constexpr auto found1 = std::ranges::find_end(
        secret.cbegin(), secret.cend(), wanted.cbegin(), wanted.cend());
    print(secret, found1);
    constexpr auto found2 = std::ranges::find_end(secret, "word"sv);
    print(secret, found2);
    const auto found3 = std::ranges::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 = std::ranges::find_end(secret, "SWORD"sv, {}, {},
        [](char c) { return std::tolower(c); }); // projects the 2nd range
    print(secret, found4);
    static_assert(std::ranges::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)
                ^^^^^

참고 항목

특정 조건을 만족하는 마지막 요소를 찾음
(알고리즘 함수 객체)
특정 조건을 만족하는 첫 번째 요소를 찾음
(알고리즘 함수 객체)
요소 집합 중 하나를 검색함
(알고리즘 함수 객체)
동일한(또는 주어진 조건자를 만족하는) 첫 번째 인접한 두 항목을 찾음
(알고리즘 함수 객체)
요소 범위의 첫 번째 발생을 검색함
(알고리즘 함수 객체)
범위 내 요소의 연속된 복사본 개수의 첫 번째 발생을 검색함
(알고리즘 함수 객체)
특정 범위에서 요소 시퀀스의 마지막 발생을 찾음
(함수 템플릿)