一 简介
- 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
本文详细介绍了C++11中引入的std::begin和std::end函数,它们用于访问容器元素,包括不同类型的容器如数组、vector和initializer_list。文章通过代码示例展示了如何使用这些函数,并解释了其在C++14和C++17中的改进。
 Range Access&spm=1001.2101.3001.5002&articleId=105692111&d=1&t=3&u=a96c327b72234c33a2ce8fde83b799e7)
677

被折叠的 条评论
为什么被折叠?



