std::end, std::cend
来自 cppreference.cn
定义于头文件 <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) (constexpr 始于 C++17) |
template< class C > auto end( const C& c ) -> decltype(c.end()); |
(2) | (始于 C++11) (constexpr 始于 C++17) |
template< class T, std::size_t N > T* end( T (&array)[N] ); |
(3) | (始于 C++11) (noexcept 始于 C++14) (constexpr 始于 C++14) |
template< class C > constexpr auto cend( const C& c ) noexcept(/* 见下文 */) |
(4) | (始于 C++14) |
返回给定范围的末尾(即最后一个元素之后一个元素)的迭代器。
1,2) 返回 c.end(),它通常是表示为 c 的序列的末尾之后一个位置的迭代器。
3) 返回指向 array 末尾的指针。
4) 返回 std::end(c),其中 c 始终被视为 const 限定。
目录 |
[编辑] 参数
c | - | 具有 end 成员函数的容器或视图 |
array | - | 任意类型的数组 |
[编辑] 返回值
1,2) c.end()
3) array + N
4) c.end()
[编辑] 异常
4)
noexcept 规范:
noexcept(noexcept(std::end(c)))
[编辑] 重载
可以为不公开合适的 end()
成员函数但可以迭代的类和枚举提供 end
的自定义重载。标准库已提供以下重载
特化 std::end (函数模板) | |
(C++11) |
特化 std::end (函数模板) |
基于范围的 for 循环支持 (函数) | |
基于范围的 for 循环支持 (函数) |
类似于 swap
的用法(在 可交换 (Swappable) 中描述),在泛型上下文中典型地使用 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); }
通过实参依赖查找 (ADL) 找到的 |
(始于 C++20) |
[编辑] 注意
非数组重载完全反映了 C::end() 的行为。如果成员函数没有合理的实现,则其效果可能会令人惊讶。
引入 std::cend
是为了统一成员和非成员范围访问。另请参见 LWG issue 2128。
如果 C
是浅const视图,则 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) |
返回指向容器或数组开头的迭代器 (函数模板) |
(C++20) |
返回指示范围末尾的哨位 (自定义点对象) |
(C++20) |
返回指示只读范围末尾的哨位 (自定义点对象) |