std::begin, std::cbegin
来自 cppreference.cn
< cpp | 迭代器 (iterator)
定义于头文件 <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 begin( C& c ) -> decltype(c.begin()); |
(1) | (C++11 起) (自 C++17 起为 constexpr) |
template< class C > auto begin( const C& c ) -> decltype(c.begin()); |
(2) | (C++11 起) (自 C++17 起为 constexpr) |
template< class T, std::size_t N > T* begin( T (&array)[N] ); |
(3) | (C++11 起) (C++14 起无异常) (C++14 起为 constexpr) |
template< class C > constexpr auto cbegin( const C& c noexcept(/* 见下文 */) |
(4) | (C++14 起) |
返回给定范围的起始迭代器。
1,2) 返回 c.begin(),它通常是表示 c 的序列的起始迭代器。
3) 返回 array 的起始指针。
4) 返回 std::begin(c),其中 c 始终被视为 const 限定。
目录 |
[编辑] 参数
c | - | 带有 begin 成员函数的容器或视图 |
array | - | 任意类型的数组 |
[编辑] 返回值
1,2) c.begin()
3) array
4) c.begin()
[编辑] 异常
4)
noexcept 规范:
noexcept(noexcept(std::begin(c)))
[编辑] 重载
对于不暴露合适的 begin()
成员函数但可迭代的类和枚举,可以提供 begin
的自定义重载。标准库已经提供了以下重载
重载 std::begin (函数模板) | |
(C++11) |
重载 std::begin (函数模板) |
支持基于范围的 for 循环 (函数) | |
支持基于范围的 for 循环 (函数) |
与 swap
的用法类似(在可交换 (Swappable) 中描述),在泛型上下文中 begin
函数的典型用法等价于 using std::begin; begin(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); while (it != end_it) { f(*it); ++it; } }
通过实参依赖查找 (argument-dependent lookup) 找到的 |
(C++20 起) |
[编辑] 注解
非数组重载精确地反映了 C::begin
的行为。如果成员函数没有合理的实现,它们的效果可能会令人惊讶。
引入 std::cbegin
是为了统一成员和非成员范围访问。另见 LWG issue 2128。
如果 C
是浅 const 视图,std::cbegin
可能会返回一个可变迭代器。这种行为对某些用户来说是意想不到的。另见 P2276 和 P2278。
[编辑] 示例
运行此代码
#include <iostream> #include <iterator> #include <vector> int main() { std::vector<int> v = {3, 1, 4}; auto vi = std::begin(v); std::cout << std::showpos << *vi << '\n'; int a[] = {-5, 10, 15}; auto ai = std::begin(a); std::cout << *ai << '\n'; }
输出
+3 -5
[编辑] 参阅
(C++11)(C++14) |
返回指向容器或数组末尾的迭代器 (函数模板) |
(C++20) |
返回指向范围开头的迭代器 (定制点对象) |
(C++20) |
返回只读范围的起始迭代器 (定制点对象) |