std::begin, std::cbegin
来自cppreference.com
<tbody>
</tbody>
| 在标头 <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 起为 noexcept) (C++14 起为 constexpr) |
template< class C > constexpr auto cbegin( const C& c ) noexcept(/* 见下文 */) -> decltype(std::begin(c)); |
(4) | (C++14 起) |
返回指向给定范围起始的迭代器。
1,2) 返回
c.begin(),它通常是指向 c 所代表的序列起始的迭代器。3) 返回指向
array 起始的指针。4) 返回
std::begin(c),这里 c 始终被视为 const 限定。参数
| c | - | 带 begin 成员函数的容器或视图
|
| array | - | 任意类型的数组 |
返回值
1,2)
c.begin()3)
array4)
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);,这允许实参依赖查找为用户定义类型所选的重载和标准库函数模板出现于同一重载集中。
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;
}
}
|
实参依赖查找找到的 |
(C++20 起) |
注解
非数组重载准确地反映了 C::begin 的行为。如果该成员函数的实现不合理,那么就会有意外的效果。
std::cbegin 是为统一成员与非成员的范围访问而引入的。参阅 LWG 问题 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) |
返回指向只读范围起始的迭代器 (定制点对象) |