C++ begin() / end() functions
begin and end is the most important iterator function in list, used toget the begin and end iterators of the linked list.
begin and end are member functions of the container class:
beginreturns an iterator pointing to the first element of the linked listiteratorendreturns an iterator pointing to the position after the last element of the linked listiterator(sentinel iterator)
These two functions are the foundation of C++ standard library algorithms and range-based for loops.
Word meaning: begin means 'begin',end means 'end'.
Basic syntax and parameters
Syntax format
iterator begin();
const_iterator begin() const;
iterator end();
const_iterator end() const;
Function description
- Return Value:
begin()returns an iterator pointing to the first element,end()returns the sentinel iterator.
Example
Example 1: Traverse the linked list
Example
#include
#include
int
main
(
)
{
std
::
list
<
int
numbers
=
{
10
,
20
,
30
,
40
,
50
};
// Traverse using iterators
std
::
cout
<<
"Traverse using iterators: "
;
for
(
auto
it
=
numbers.
begin
(
)
;
it
!
=
numbers.
end
(
)
;
++
it
)
{
std
::
cout
<<
it
<<
" "
;
}
std
::
cout
<<
std
::
endl
;
return
0
;
}
Expected output:
使用迭代器遍历: 10 20 30 40 50
Example 2: Range-based for loop
Example
#include
#include
int
main
(
)
{
std
::
list
<
std
::
string
names
=
{
"Alice"
,
"Bob"
,
"Charlie"
}
;
std
::
cout
<<
"Range-based for loop: "
;
for
(
const
auto
&
name
:
names
)
{
std
::
cout
<<
name
<<
" "
;
}
std
::
cout
<<
std
::
endl
;
return
0
;
}
Expected output:
范围 for 循环: Alice Bob Charlie
Example 3: Using STL algorithms
Example
#include
#include
#include
int
main
(
)
{
std
::
list
<
int
numbers
=
{
5
,
2
,
8
,
1
,
9
,
3
};
// Sort
numbers.
sort
(
)
;
std
::
cout
<<
"After sorting: "
;
for
(
int
n
:
numbers
)
std
::
cout
<<
n
<<
" "
;
std
::
cout
<<
std
::
endl
;
// Find
auto
it
=
std
::
find
(
numbers.
begin
(
)
, numbers.
end
(
)
,
8
)
;
if
(
it
!
=
numbers.
end
(
)
)
{
std
::
cout
<<
"Found: "
<<
it
<<
std
::
endl
;
}
return
0
;
}
Expected output:
排序后: 1 2 3 5 8 9
找到: 8
Example 4: Reverse iterators
Example
#include
#include
int
main
(
)
{
std
::
list
<
int
numbers
=
{
1
,
2
,
3
,
4
,
5
};
std
::
cout
<<
"Forward: "
;
for
(
auto
it
=
numbers.
begin
(
)
;
it
!
=
numbers.
end
(
)
;
++
it
)
{
std
::
cout
<<
it
<<
" "
;
}
std
::
cout
<<
std
::
endl
;
std
::
cout
<<
"Reverse: "
;
for
(
auto
it
=
numbers.
rbegin
(
)
;
it
!
=
numbers.
rend
(
)
;
++
it
)
{
std
::
cout
<<
it
<<
" "
;
}
std
::
cout
<<
std
::
endl
;
return
0
;
}
Expected output:
正向: 1 2 3 4 5
反向: 5 4 3 2 1
The C++ container class