C++ std::list::begin
The std::list::begin
function returns an iterator pointing to the first element of a std::list
. This allows traversal of the list from the beginning using iterators. If the list is empty, the returned iterator is equal to end()
.
Syntax of std::list::begin
</>
Copy
iterator begin() noexcept;
const_iterator begin() const noexcept;
Parameters
The std::list::begin
function does not take any parameters.
Return Value
Returns an iterator (or a constant iterator for const
lists) pointing to the first element of the list. If the list is empty, the returned iterator is equal to std::list::end
.
Exceptions
The std::list::begin
function does not throw exceptions as it is marked noexcept
.
Examples for std::list::begin
Example 1: Traversing a List Using std::list::begin
This example demonstrates iterating through the elements of a std::list
using begin()
and end()
:
</>
Copy
#include <iostream>
#include <list>
int main() {
std::list<int> myList = {10, 20, 30, 40, 50};
std::cout << "List elements: ";
for (auto it = myList.begin(); it != myList.end(); ++it) {
std::cout << *it << " ";
}
std::cout << std::endl;
return 0;
}
Explanation:
- Define a list: A
std::list
namedmyList
is initialized with the elements{10, 20, 30, 40, 50}
. - Iterate using iterators: The program uses a
for
loop to iterate through the elements of the list using iterators:myList.begin()
returns an iterator pointing to the first element of the list.myList.end()
returns an iterator pointing to one past the last element of the list.- During each iteration, the dereference operator (
*it
) accesses the value of the element at the current iterator position.
- Access elements: All the elements of the list are printed in sequence, separated by spaces.
Output:
List elements: 10 20 30 40 50
Example 2: Modifying Elements Using std::list::begin
This example demonstrates how to modify elements of a std::list
using begin()
:
</>
Copy
#include <iostream>
#include <list>
int main() {
std::list<int> myList = {1, 2, 3, 4, 5};
auto it = myList.begin(); // Get an iterator to the first element
*it = 10; // Modify the first element
std::cout << "Modified list: ";
for (const auto& elem : myList) {
std::cout << elem << " ";
}
std::cout << std::endl;
return 0;
}
Explanation:
- Define a list: A
std::list
namedmyList
is initialized with elements{1, 2, 3, 4, 5}
. - Get an iterator: The
begin()
function provides an iterator pointing to the first element of the list. - Modify the element: The first element is modified by dereferencing the iterator and assigning a new value (
10
). - Output the modified list: The updated list is printed using a range-based for loop.
Output:
Modified list: 10 2 3 4 5