std::begin, std::cbegin
提供: cppreference.com
| ヘッダ <iterator> で定義
|
||
| (1) | ||
| template< class C > auto begin( C& c ) -> decltype(c.begin()); |
(C++11以上) (C++17未満) |
|
| template< class C > constexpr auto begin( C& c ) -> decltype(c.begin()); |
(C++17以上) | |
| (1) | ||
| template< class C > auto begin( const C& c ) -> decltype(c.begin()); |
(C++11以上) (C++17未満) |
|
| template< class C > constexpr auto begin( const C& c ) -> decltype(c.begin()); |
(C++17以上) | |
| (2) | ||
| template< class T, std::size_t N > T* begin( T (&array)[N] ); |
(C++11以上) (C++14未満) |
|
| template< class T, std::size_t N > constexpr T* begin( T (&array)[N] ) noexcept; |
(C++14以上) | |
| template< class C > constexpr auto cbegin( const C& c ) noexcept(/* see below */) |
(3) | (C++14以上) |
指定されたコンテナ c または配列 array の先頭を指すイテレータを返します。 これらのテンプレートは C::begin() が妥当な実装を持つことを当てにしています。
1) 正確に c.begin() を返します。 これは一般的には
c によって表されるシーケンスの先頭を指すイテレータです。 C が標準の Container の場合、 c が const 修飾されていなければ C::iterator を返し、そうでなければ C::const_iterator を返します。2)
array の先頭を指すポインタを返します。3) 正確に std::begin(c) を返します。
c は常に const 修飾されたものとして扱われます。 C が標準の Container の場合、これは常に C::const_iterator を返します。
| This section is incomplete Reason: an explanation why cbegin was introduced |
目次 |
[編集] 引数
| c | - | メンバ関数 begin を持つコンテナ
|
| array | - | 任意の型の配列 |
[編集] 戻り値
c または array の先頭を指すイテレータ。
[編集] 例外
3)
noexcept 指定:
noexcept(noexcept(std::begin(c)))
[編集] ノート
<iterator> がインクルードされた場合に加えて <array>、 <deque>、 <forward_list>、 <list>、 <map>、 <regex>、 <set>、 <span> (C++20以上)、 <string>、 <string_view> (C++17以上)、 <unordered_map>、 <unordered_set>、 <vector> のいずれかのヘッダがインクルードされた場合も、 std::begin および std::cbegin が利用可能になることが保証されています。
[編集] ユーザ定義のオーバーロード
適切な 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; } }
[編集] 例
Run this code
#include <iostream> #include <vector> #include <iterator> int main() { std::vector<int> v = { 3, 1, 4 }; auto vi = std::begin(v); std::cout << *vi << '\n'; int a[] = { -5, 10, 15 }; auto ai = std::begin(a); std::cout << *ai << '\n'; }
出力:
3 -5
[編集] 関連項目
| (C++11)(C++14) |
コンテナまたは配列の終端を指すイテレータを返します (関数) |

