std::forward_list before_begin()/cbefore_begin() 方法
- 自 C++11 起
// Non-const version
iterator begin() noexcept;
// Const version
const_iterator begin() const noexcept;
const_iterator cbegin() const noexcept;
返回指向数组末尾之后元素的迭代器。指向容器第一个元素之前的元素。
未定义行为
此元素充当占位符,尝试访问它会导致未定义行为
.唯一的用法是出现在函数insert_after()
、emplace_after()
、erase_after()
、splice_after()
和递增运算符中:递增 before-begin 迭代器会得到与 begin/cbegin()
相同的迭代器。
参数
(无)
返回值
指向第一个元素之前的元素的迭代器。
复杂度
常数 - O(1)。
before_begin 和 cbefore_begin 之间的区别
对于 const 容器 c
,before_begin
和 cbefore_begin
是相同的 - c.before_begin() == c.cbefore_begin()
对于非常量类型c
的容器,它们返回不同的迭代器
- 非常量容器
- 常量容器
- before_begin
- cbefore_begin
#include <forward_list>
int main()
{
std::forward_list<int> arr = {1, 2, 3, 4, 5};
auto it = arr.before_begin(); // Type: std::forward_list<int>::iterator
*std::next(it) = 5; // ✔ Ok
}
#include <forward_list>
int main()
{
std::forward_list<int> arr = {1, 2, 3, 4, 5};
auto it = arr.cbefore_begin(); // Type: std::forward_list<int>::const_iterator
*std::next(it) = 5; // ❌ Error!
}
- before_begin
- cbefore_begin
#include <forward_list>
int main()
{
const std::forward_list<int> arr = {1, 2, 3, 4, 5};
auto it = arr.before_begin(); // Type: std::forward_list<int>::const_iterator
*std::next(it) = 5; // ❌ Error!
}
#include <forward_list>
int main()
{
const std::forward_list<int> arr = {1, 2, 3, 4, 5};
auto it = arr.cbefore_begin(); // Type: std::forward_list<int>::const_iterator
*std::next(it) = 5; // ❌ Error!
}
示例
重要
本节需要改进。您可以通过编辑此文档页面来帮助我们。