std::ranges::find_last, std::ranges::find_last_if, std::ranges::find_last_if_not

来自cppreference.com
< cpp‎ | algorithm‎ | ranges
 
 
算法库
受约束算法及范围上的算法 (C++20)
包含算法例如 ranges::copy, ranges::sort, ...
执行策略 (C++17)
排序和相关操作
划分操作
排序操作
二分搜索操作(在已划分范围上)
集合操作(在有序范围上)
归并操作(在有序范围上)
堆操作
最小/最大操作
(C++11)
(C++17)
字典序比较操作
排列操作
C 库

数值运算
(C++11)                       
在未初始化内存上的操作
 
受约束算法
本菜单中的所有名字均属于命名空间 std::ranges
不修改序列的操作
修改序列的操作
划分操作
排序操作
二分搜索操作(在有序范围上)
       
       
集合操作(在有序范围上)
堆操作
最小/最大操作
       
       
排列操作
折叠操作
数值操作
(C++23)            
未初始化存储上的操作
返回类型
 
在标头 <algorithm> 定义
调用签名
(1)
template< std::forward_iterator I, std::sentinel_for<I> S,

          class T,
          class Proj = std::identity >
requires std::indirect_binary_predicate
             <ranges::equal_to, std::projected<I, Proj>, const T*>
constexpr ranges::subrange<I>

    find_last( I first, S last, const T& value, Proj proj = {} );
(C++23 起)
(C++26 前)
template< std::forward_iterator I, std::sentinel_for<I> S,

          class Proj = std::identity,
          class T = std::projected_value_t<I, Proj> >
requires std::indirect_binary_predicate
             <ranges::equal_to, std::projected<I, Proj>, const T*>
constexpr ranges::subrange<I>

    find_last( I first, S last, const T& value, Proj proj = {} );
(C++26 起)
(2)
template< ranges::forward_range R,

          class T,
          class Proj = std::identity >
requires std::indirect_binary_predicate
             <ranges::equal_to,
              std::projected<ranges::iterator_t<R>, Proj>, const T*>
constexpr ranges::borrowed_subrange_t<R>

    find_last( R&& r, const T& value, Proj proj = {} );
(C++23 起)
(C++26 前)
template< ranges::forward_range R,

          class Proj = std::identity,
          class T = std::projected_value_t<iterator_t<R>, Proj> >
requires std::indirect_binary_predicate
             <ranges::equal_to,
              std::projected<ranges::iterator_t<R>, Proj>, const T*>
constexpr ranges::borrowed_subrange_t<R>

    find_last( R&& r, const T& value, Proj proj = {} );
(C++26 起)
template< std::forward_iterator I, std::sentinel_for<I> S,

          class Proj = std::identity,
          std::indirect_unary_predicate<std::projected<I, Proj>> Pred >
constexpr ranges::subrange<I>

    find_last_if( I first, S last, Pred pred, Proj proj = {} );
(3) (C++23 起)
template< ranges::forward_range R,

          class Proj = std::identity,
          std::indirect_unary_predicate
              <std::projected<ranges::iterator_t<R>, Proj>> Pred >
constexpr ranges::borrowed_subrange_t<R>

    find_last_if( R&& r, Pred pred, Proj proj = {} );
(4) (C++23 起)
template< std::forward_iterator I, std::sentinel_for<I> S,

          class Proj = std::identity,
          std::indirect_unary_predicate<std::projected<I, Proj>> Pred >
constexpr ranges::subrange<I>

    find_last_if_not( I first, S last, Pred pred, Proj proj = {} );
(5) (C++23 起)
template< ranges::forward_range R,

          class Proj = std::identity,
          std::indirect_unary_predicate
              <std::projected<ranges::iterator_t<R>, Proj>> Pred >
constexpr ranges::borrowed_subrange_t<R>

    find_last_if_not( R&& r, Pred pred, Proj proj = {} );
(6) (C++23 起)

返回范围 [firstlast) 中符合特定条件的最后一个元素:

1) find_last 搜索等于 value 的元素。
3) find_last_if 搜索范围 [firstlast) 中谓词 pred 为之返回 true 的最后一个元素。
5) find_last_if_not 搜索范围 [firstlast) 中谓词 pred 为之返回 false 的最后一个元素。
2,4,6)(1,3,5) 相同,但使用 r 作为源范围,就像使用 ranges::begin(r) 作为 firstranges::end(r) 作为 last 一样。

此页面上描述的函数式实体是 niebloid,即:

实践中,可以作为函数对象,或者用某些特殊编译器扩展实现它们。

参数

first, last - 要检查的元素的范围
r - 要检查的元素的范围
value - 和元素进行比较的值
pred - 应用到投影后元素的谓词
proj - 应用到元素的投影

返回值

1,2,3)i[firstlast) 范围内使得 Etrue 的最后一个迭代器。
如果不存在这样的迭代器,那么就会返回 ranges::subrange<I>{i, last},或 ranges::subrange<I>{last, last}
1) Ebool(std::invoke(proj, *i) == value)
3) Ebool(std::invoke(pred, std::invoke(proj, *i)))
5) Ebool(!std::invoke(pred, std::invoke(proj, *i)))
2,4,6)(1,3,5) 类似,但是返回值类型是 ranges::borrowed_subrange_t<I>

复杂度

最多应用 last - first 次谓词和投影。

注解

如果 ranges::find_lastranges::find_last_ifranges::find_last_if_notIbidirectional_iterator 或(更好的)random_access_iterator,则它们在通用实现上的效率更高。

功能特性测试 标准 功能特性
__cpp_lib_ranges_find_last 202207L (C++23) ranges::find_last
ranges::find_last_if
ranges::find_last_if_not
__cpp_lib_algorithm_default_value_type 202403L (C++26) 算法的列表初始化 (1,2)

可能的实现

这个实现只展示 Iforward_iterator 时较慢的算法。

find_last (1,2)
struct find_last_fn
{
    template<std::forward_iterator I, std::sentinel_for<I> S,
             class Proj = std::identity,
             class T = std::projected_value_t<iterator_t<R>, Proj>>
    requires std::indirect_binary_predicate
                 <ranges::equal_to, std::projected<I, Proj>, const T*>
    constexpr ranges::subrange<I>
        operator()(I first, S last, const T &value, Proj proj = {}) const
    {
        // 注意:如果 I 只是 forward_iterator,那么只能从头走到尾。
        std::optional<I> found;
        for (; first != last; ++first)
            if (std::invoke(proj, *first) == value)
                found = first;
 
        if (!found)
            return {first, first};
 
        return {*found, std::ranges::next(*found, last)};
    }
 
    template<ranges::forward_range R,
             class Proj = std::identity,
             class T = std::projected_value_t<iterator_t<R>, Proj>>
    requires std::indirect_binary_predicate
                 <ranges::equal_to,
                  std::projected<ranges::iterator_t<R>, Proj>, const T*>
    constexpr ranges::borrowed_subrange_t<R>
        operator()(R&& r, const T &value, Proj proj = {}) const
    {
        return this->operator()(ranges::begin(r), ranges::end(r), value, std::ref(proj));
    }
};
 
inline constexpr find_last_fn find_last;
find_last_if (3,4)
struct find_last_if_fn
{
    template<std::forward_iterator I, std::sentinel_for<I> S,
             class Proj = std::identity,
             std::indirect_unary_predicate<std::projected<I, Proj>> Pred>
    constexpr ranges::subrange<I>
        operator()(I first, S last, Pred pred, Proj proj = {}) const
    {
        // 注意:如果 I 只是 forward_iterator,那么只能从头走到尾。
        std::optional<I> found;
        for (; first != last; ++first)
            if (std::invoke(pred, std::invoke(proj, *first)))
                found = first;
 
        if (!found)
            return {first, first};
 
        return {*found, std::ranges::next(*found, last)};
    }
 
    template<ranges::forward_range R, class Proj = std::identity,
             std::indirect_unary_predicate
                 <std::projected<ranges::iterator_t<R>, Proj>> Pred>
    constexpr ranges::borrowed_subrange_t<R>
        operator()(R&& r, Pred pred, Proj proj = {}) const
    {
        return this->operator()(ranges::begin(r), ranges::end(r),
                                std::ref(pred), std::ref(proj));
    }
};
 
inline constexpr find_last_if_fn find_last_if;
find_last_if_not (5,6)
struct find_last_if_not_fn
{
    template<std::forward_iterator I, std::sentinel_for<I> S,
             class Proj = std::identity,
             std::indirect_unary_predicate<std::projected<I, Proj>> Pred>
    constexpr ranges::subrange<I>
        operator()(I first, S last, Pred pred, Proj proj = {}) const
    {
        // 注意:如果 I 只是 forward_iterator,那么只能从头走到尾。
        std::optional<I> found;
        for (; first != last; ++first)
            if (!std::invoke(pred, std::invoke(proj, *first)))
                found = first;
 
        if (!found)
            return {first, first};
 
        return {*found, std::ranges::next(*found, last)};
    }
 
    template<ranges::forward_range R, class Proj = std::identity,
             std::indirect_unary_predicate
                 <std::projected<ranges::iterator_t<R>, Proj>> Pred>
    constexpr ranges::borrowed_subrange_t<R>
        operator()(R&& r, Pred pred, Proj proj = {}) const
    {
        return this->operator()(ranges::begin(r), ranges::end(r),
                                std::ref(pred), std::ref(proj));
    }
};
 
inline constexpr find_last_if_not_fn find_last_if_not;

示例

#include <algorithm>
#include <cassert>
#include <forward_list>
#include <iomanip>
#include <iostream>
#include <string_view>
 
int main()
{
    namespace ranges = std::ranges;
 
    constexpr static auto v = {1, 2, 3, 1, 2, 3, 1, 2};
 
    {
        constexpr auto i1 = ranges::find_last(v.begin(), v.end(), 3);
        constexpr auto i2 = ranges::find_last(v, 3);
        static_assert(ranges::distance(v.begin(), i1.begin()) == 5);
        static_assert(ranges::distance(v.begin(), i2.begin()) == 5);
    }
    {
        constexpr auto i1 = ranges::find_last(v.begin(), v.end(), -3);
        constexpr auto i2 = ranges::find_last(v, -3);
        static_assert(i1.begin() == v.end());
        static_assert(i2.begin() == v.end());
    }
 
    auto abs = [](int x) { return x < 0 ? -x : x; };
 
    {
        auto pred = [](int x) { return x == 3; };
        constexpr auto i1 = ranges::find_last_if(v.begin(), v.end(), pred, abs);
        constexpr auto i2 = ranges::find_last_if(v, pred, abs);
        static_assert(ranges::distance(v.begin(), i1.begin()) == 5);
        static_assert(ranges::distance(v.begin(), i2.begin()) == 5);
    }
    {
        auto pred = [](int x) { return x == -3; };
        constexpr auto i1 = ranges::find_last_if(v.begin(), v.end(), pred, abs);
        constexpr auto i2 = ranges::find_last_if(v, pred, abs);
        static_assert(i1.begin() == v.end());
        static_assert(i2.begin() == v.end());
    }
 
    {
        auto pred = [](int x) { return x == 1 or x == 2; };
        constexpr auto i1 = ranges::find_last_if_not(v.begin(), v.end(), pred, abs);
        constexpr auto i2 = ranges::find_last_if_not(v, pred, abs);
        static_assert(ranges::distance(v.begin(), i1.begin()) == 5);
        static_assert(ranges::distance(v.begin(), i2.begin()) == 5);
    }
    {
        auto pred = [](int x) { return x == 1 or x == 2 or x == 3; };
        constexpr auto i1 = ranges::find_last_if_not(v.begin(), v.end(), pred, abs);
        constexpr auto i2 = ranges::find_last_if_not(v, pred, abs);
        static_assert(i1.begin() == v.end());
        static_assert(i2.begin() == v.end());
    }
 
    using P = std::pair<std::string_view, int>;
    std::forward_list<P> list
    {
        {"one", 1}, {"two", 2}, {"three", 3},
        {"one", 4}, {"two", 5}, {"three", 6},
    };
    auto cmp_one = [](const std::string_view &s) { return s == "one"; };
 
    // 寻找满足比较器的最后一个元素,其按 pair::first 投影
    const auto subrange = ranges::find_last_if(list, cmp_one, &P::first);
 
    std::cout << "所找到的元素和其后的尾部为:\n";
    for (P const& e : subrange)
        std::cout << '{' << std::quoted(e.first) << ", " << e.second << "} ";
    std::cout << '\n';
 
#if __cpp_lib_algorithm_default_value_type
    const auto i3 = ranges::find_last(list, {"three", 3}); // (2) C++26
#else
    const auto i3 = ranges::find_last(list, P{"three", 3}); // (2) C++23
#endif
    assert(i3.begin()->first == "three" && i3.begin()->second == 3);
}

输出:

所找到的元素和其后的尾部为:
{"one", 4} {"two", 5} {"three", 6}

参阅

查找特定范围中最后出现的元素序列
(niebloid)
查找满足特定条件的的第一个元素
(niebloid)
搜索一个元素范围的首次出现
(niebloid)
若一个序列是另一个的子列则返回 true
(niebloid)
确定元素是否存在于某范围中
(niebloid)
检查范围是否包含给定的元素或子范围
(niebloid)