begin
指定されたコンテナーの最初の要素への反復子を取得します。
template<class Container>
auto begin(Container& cont)
-> decltype(cont.begin());
template<class Container>
auto begin(const Container& cont)
-> decltype(cont.begin());
template<class Ty, class Size>
Ty *begin(Ty (&array)[Size]);
パラメーター
cont
コンテナー。array
Ty 型のオブジェクトの配列。
戻り値
最初の 2 つのテンプレート関数は、cont.begin() を返します。 最初の関数は定数ではなく、2 番目の関数は定数です。
3 番目のテンプレート関数は array を返します。
使用例
さらに、より一般的な動作が必要な場合は、コンテナーのメンバーである begin() の代わりにこのテンプレート関数を使用することをお勧めします。
// cl.exe /EHsc /nologo /W4 /MTd
#include <algorithm>
#include <functional>
#include <iostream>
#include <iterator>
#include <vector>
template <typename C> void reverse_sort(C& c) {
using std::begin;
using std::end;
std::sort(begin(c), end(c), std::greater<>());
}
template <typename C> void print(const C& c) {
for (const auto& e : c) {
std::cout << e << " ";
}
std::cout << "\n";
}
int main() {
std::vector<int> v = { 11, 34, 17, 52, 26, 13, 40, 20, 10, 5, 16, 8, 4, 2, 1 };
print(v);
reverse_sort(v);
print(v);
std::cout << "--\n";
int arr[] = { 23, 70, 35, 106, 53, 160, 80, 40, 20, 10, 5, 16, 8, 4, 2, 1 };
print(arr);
reverse_sort(arr);
print(arr);
}
Output:
11 34 17 52 26 13 40 20 10 5 16 8 4 2 1
52 40 34 26 20 17 16 13 11 10 8 5 4 2 1
--
23 70 35 106 53 160 80 40 20 10 5 16 8 4 2 1
160 106 80 70 53 40 35 23 20 16 10 8 5 4 2 1
reverse_sort 関数は、通常の配列に加えて、任意の種類のコンテナーをサポートします。これは、メンバーではないバージョンの begin() を呼び出すためです。 コンテナーのメンバーである begin() を使用するために reverse_sort がコーディングされた場合、次のようになります。
template <typename C> void reverse_sort(C& c) {
using std::begin;
using std::end;
std::sort(c.begin(), c.end(), std::greater<>());
}
その後、配列を渡すと、このコンパイラ エラーが発生します。
error C2228: left of '.begin' must have class/struct/union
必要条件
ヘッダー:<iterator>
名前空間: std