一 简介
- C++11开始, 提供 std::begin 、std::end 对容器元素进行访问。
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 起)(1)
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 起) (2)
template< class C >
constexpr auto cbegin( const C& c ) noexcept()
-> decltype(std::begin(c));(C++14 起)(3)
二 例子
#include <iostream>
#include <string>
#include <vector>
#include <initializer_list>
#include <iterator>
template <typename T>
void print(const std::string& pre,
const T& it_begin,
const T& it_end) {
std::cout << pre << ": ";
auto it = it_begin;
while(it != it_end) {
std::cout << *it << " ";
++it;
}
std::cout << std::endl;
}
int main() {
int sz[] = {1,2,3,4,5,6,7,8,9};
// C++11
print("sz1", std::begin(sz), std::end(sz));
// c++14
print("sz2", std::cbegin(sz), std::cend(sz));
print("sz3", std::rbegin(sz), std::rend(sz));
print("sz4", std::crbegin(sz), std::crend(sz));
std::vector<int> vc{1,2,3,4,5,6,7,8,9};
print("vc", std::begin(vc), std::end(vc));
std::initializer_list<int> lt{1, 2, 3, 4, 5, 6, 7, 8, 9};
print("lt", std::begin(lt), std::end(lt));
std::cin.get();
return 0;
}
结果:
sz1: 1 2 3 4 5 6 7 8 9
sz2: 1 2 3 4 5 6 7 8 9
sz3: 9 8 7 6 5 4 3 2 1
sz4: 9 8 7 6 5 4 3 2 1
vc: 1 2 3 4 5 6 7 8 9
lt: 1 2 3 4 5 6 7 8 9