std::array begin()/cbegin() 方法
- 自 C++17 起
- C++17 之前
// Non-const version
constexpr iterator begin() noexcept;
// Const version
constexpr const_iterator begin() const noexcept;
constexpr const_iterator cbegin() const noexcept;
// Non-const version
iterator begin() noexcept;
// Const version
const_iterator begin() const noexcept;
const_iterator cbegin() const noexcept;
返回指向数组末尾之后元素的迭代器。
指向数组的第一个元素。如果数组为空,返回的迭代器将等于end()
。
参数
(无)
返回值
指向第一个元素的迭代器。
复杂度
常数。
备注
对于容器c
,表达式*c.begin()
等效于c.front()
。
begin 和 cbegin 的区别
对于 const 容器 c
,begin 和 cbegin 是相同的 - c.begin() == c.cbegin()
对于非常量类型c
的容器,它们返回不同的迭代器
- 非常量容器
- 常量容器
- Begin
- cbegin
#include <array>
int main()
{
std::array<int, 5> arr = {1, 2, 3, 4, 5};
auto it = arr.begin(); // Type: std::array<int, 5>::iterator
*it = 5; // ✔ Ok
}
#include <array>
int main()
{
std::array<int, 5> arr = {1, 2, 3, 4, 5};
auto it = arr.cbegin(); // Type: std::array<int, 5>::const_iterator
// ❌ Error!
*it = 5;
}
- Begin
- cbegin
#include <array>
int main()
{
const std::array<int, 5> arr = {1, 2, 3, 4, 5};
auto it = arr.begin(); // Type: std::array<int, 5>::const_iterator
// ❌ Error!
*it = 5;
}
#include <array>
int main()
{
const std::array<int, 5> arr = {1, 2, 3, 4, 5};
auto it = arr.cbegin(); // Type: std::array<int, 5>::const_iterator
// ❌ Error!
*it = 5;
}
示例
Main.cpp
#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; // => undefined behaviour at run-time
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; // compile-time error:
// read-only variable is not assignable
// print out all elements
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
// ❌ Compile-time error: read-only variable is not assignable
*constants.begin() = 'Z';
}
可能输出
1) true true
2) false false
3) 5 5
4) 1
5) 1 2 3 4