CppDS.com

C++ 98 11 14 17 20 手册

std::array<T,N>::begin, std::array<T,N>::cbegin

来自cppreference.com
< cpp‎ | container‎ | array

iterator begin() noexcept;
(C++17 前)
constexpr iterator begin() noexcept;
(C++17 起)
const_iterator begin() const noexcept;
(C++17 前)
constexpr const_iterator begin() const noexcept;
(C++17 起)
const_iterator cbegin() const noexcept;
(C++17 前)
constexpr const_iterator cbegin() const noexcept;
(C++17 起)

返回指向 array 首元素的迭代器。

array 为空,则返回的迭代器将等于 end()

range-begin-end.svg

参数

(无)

返回值

指向首元素的迭代器。

复杂度

常数。


示例

#include <array>
#include <iostream>
#include <algorithm>
#include <iomanip>
 
int main()
{
    std::cout << std::boolalpha;
 
    std::array<int, 0> empty;
    std::cout << "1) "
              << (empty.begin() == empty.end()) << ' '     // true
              << (empty.cbegin() == empty.cend()) << '\n'; // true
    // *(empty.begin()) = 42; // => 运行时的未定义行为
 
 
    std::array<int, 4> numbers{5, 2, 3, 4};
    std::cout << "2) "
              << (numbers.begin() == numbers.end()) << ' '    // false
              << (numbers.cbegin() == numbers.cend()) << '\n' // false
              << "3) "
              << *(numbers.begin()) << ' '    // 5
              << *(numbers.cbegin()) << '\n'; // 5
 
    *numbers.begin() = 1;
    std::cout << "4) " << *(numbers.begin()) << '\n'; // 1
    // *(numbers.cbegin()) = 42; // 编译时错误:
                                 // 只读变量不可赋值
 
    // 打印所有元素
    std::cout << "5) ";
    std::for_each(numbers.cbegin(), numbers.cend(), [](int x) {
       std::cout << x << ' ';
    });
    std::cout << '\n';
 
 
    constexpr std::array constants{'A', 'B', 'C'};
    static_assert(constants.begin() != constants.end());   // OK
    static_assert(constants.cbegin() != constants.cend()); // OK
    static_assert(*constants.begin() == 'A');              // OK
    static_assert(*constants.cbegin() == 'A');             // OK
    // *constants.begin() = 'Z'; // 编译时错误: 
                                 // 只读变量不可赋值
}

输出:

1) true true
2) false false
3) 5 5
4) 1
5) 1 2 3 4

参阅

返回指向末尾的迭代器
(公开成员函数)
关闭