C++11 iterator(3) Range Access

一 简介
  • 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
三 参考

cppreference

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值