std::forward_list before_begin()/cbefore_begin() method
- since C++11
// Non-const version
iterator begin() noexcept;
// Const version
const_iterator begin() const noexcept;
const_iterator cbegin() const noexcept;
Returns an iterator to the element before the first element of the container.
This element acts as a placeholder, attempting to access it results in undefined behavior
.The only usage cases are in functions insert_after()
, emplace_after()
, erase_after()
, splice_after()
and the increment operator: incrementing the before-begin iterator gives exactly the same iterator as obtained from begin/cbegin()
.
Parameters
(none)
Return value
Iterator to the element before the first element.
Complexity
Constant - O(1).
Difference between before_begin and cbefore_begin
For a const container c
, before_begin
and cbefore_begin
are the same - c.before_begin() == c.cbefore_begin()
For non-const container of type c
they return different iterators:
- Non const container
- Const container
- 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!
}
Example
This section requires improvement. You can help by editing this doc page.
Hover to see the original license.