std::array<T,N>::end, std::array<T,N>::cend
来自cppreference.com
<tbody>
</tbody>
iterator end() noexcept; |
(1) | (C++11 起) (C++17 起为 constexpr) |
const_iterator end() const noexcept; |
(2) | (C++11 起) (C++17 起为 constexpr) |
const_iterator cend() const noexcept; |
(3) | (C++11 起) (C++17 起为 constexpr) |
返回指向 array 末元素后一元素的迭代器。
此元素表现为占位符;试图访问它导致未定义行为。
返回值
指向后随最后元素的迭代器。
复杂度
常数。
示例
运行此代码
#include <algorithm>
#include <array>
#include <iomanip>
#include <iostream>
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
参阅
| 返回指向起始的迭代器 (公开成员函数) | |
(C++11)(C++14) |
返回指向容器或数组结尾的迭代器 (函数模板) |