Namespaces
Variants

std:: end, std:: cend

From cppreference.net
Iterator library
Iterator concepts
Iterator primitives
Algorithm concepts and utilities
Indirect callable concepts
Common algorithm requirements
(C++20)
(C++20)
(C++20)
Utilities
(C++20)
Iterator adaptors
Range access
(C++11) (C++14)
(C++14) (C++14)
end cend
(C++11) (C++14)
(C++14) (C++14)
(C++17) (C++20)
(C++17)
(C++17)
定义于头文件 <array>
定义于头文件 <deque>
定义于头文件 <flat_map>
定义于头文件 <flat_set>
定义于头文件 <forward_list>
定义于头文件 <inplace_vector>
定义于头文件 <iterator>
定义于头文件 <list>
定义于头文件 <map>
定义于头文件 <regex>
定义于头文件 <set>
定义于头文件 <span>
定义于头文件 <string>
定义于头文件 <string_view>
定义于头文件 <unordered_map>
定义于头文件 <unordered_set>
定义于头文件 <vector>
template < class C >
auto end ( C & c ) - > decltype ( c. end ( ) ) ;
(1) (C++11 起)
(C++17 起为 constexpr)
template < class C >
auto end ( const C & c ) - > decltype ( c. end ( ) ) ;
(2) (C++11 起)
(C++17 起为 constexpr)
template < class T, std:: size_t N >
T * end ( T ( & array ) [ N ] ) ;
(3) (C++11 起)
(C++14 起为 noexcept)
(C++14 起为 constexpr)
template < class C >

constexpr auto cend ( const C & c ) noexcept ( /* 见下文 */ )

- > decltype ( std :: end ( c ) ) ;
(4) (C++14 起)

返回指向给定范围末尾(即最后一个元素之后的元素)的迭代器。

1,2) 返回 c. end ( ) ,该迭代器通常指向 c 所表示序列的末尾后一位置。
1) C 是标准 Container ,则返回一个 C::iterator 对象。
2) C 是标准 Container ,则返回一个 C::const_iterator 对象。
3) 返回指向 array 末尾的指针。
4) 返回 std :: end ( c ) ,其中 c 始终被视为 const 限定。
C 是标准 Container ,则返回一个 C::const_iterator 对象。

range-begin-end.svg

目录

参数

c - 具有 end 成员函数的容器或视图
array - 任意类型的数组

返回值

1,2) c. end ( )
3) array + N
4) c. end ( )

异常

4)
noexcept 规范:
noexcept ( noexcept ( std :: end ( c ) ) )

重载

对于未提供合适的 end() 成员函数但仍可迭代的类和枚举,可提供自定义的 end 重载。标准库已提供以下重载:

特化 std::end
(函数模板)
特化 std::end
(函数模板)
基于范围的 for 循环支持
(函数)
基于范围的 for 循环支持
(函数)

类似于 swap 的使用方式(详见 可交换类型 ),在泛型上下文中使用 end 函数的典型做法等价于 using std :: end ; end ( arg ) ; ,这种方式允许用户定义类型的 ADL 重载和标准库函数模板同时出现在同一个重载集中。

template<typename Container, typename Function>
void for_each(Container&& cont, Function f)
{
    using std::begin;
    auto it = begin(cont);
    using std::end;
    auto end_it = end(cont);
    for (; it != end_it; ++it)
        f(*it);
}

通过 实参依赖查找 找到的 end 重载可用于自定义 std::ranges::end std::ranges::cend 及其他依赖于 std::ranges::end 的自定义指针对象的行为。

(C++20 起)

注释

非数组重载完全反映了 C :: end ( ) 的行为。若成员函数未实现合理逻辑,其效果可能会出人意料。

std::cend 的引入是为了统一成员与非成员的范围访问方式。另请参阅 LWG issue 2128

如果 C 是一个浅常量视图, std::cend 可能返回一个可变迭代器。这种行为对某些用户而言是意料之外的。另请参阅 P2276 P2278

示例

#include <algorithm>
#include <iostream>
#include <vector>
int main()
{
    std::vector<int> v = {3, 1, 4};
    if (std::find(std::begin(v), std::end(v), 5) != std::end(v))
        std::cout << "Found a 5 in vector v!\n";
    int w[] = {5, 10, 15};
    if (std::find(std::begin(w), std::end(w), 5) != std::end(w))
        std::cout << "Found a 5 in array w!\n";
}

输出:

Found a 5 in array w!

参见

(C++11) (C++14)
返回指向容器或数组起始位置的迭代器
(函数模板)
返回指示范围结尾的哨兵
(定制点对象)
返回指示只读范围结尾的哨兵
(定制点对象)