C++ std::list::end

The std::list::end function returns an iterator pointing to the position one past the last element of the std::list. This iterator is used to denote the end of the list and is not dereferenceable. It is often used in conjunction with begin() to iterate through the list.


Syntax of std::list::end

</>
Copy
iterator end() noexcept;
const_iterator end() const noexcept;

Parameters

The std::list::end function does not take any parameters.

Return Value

Returns an iterator (or a constant iterator for const lists) pointing to one past the last element of the list. This iterator is used as a marker for the end of the list.

Exceptions

The std::list::end function does not throw exceptions as it is marked noexcept.


Examples for std::list::end

Example 1: Traversing a List Using std::list::end

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:

  1. Define a list: A std::list named myList is initialized with elements {10, 20, 30, 40, 50}.
  2. Use iterators: The begin() function provides an iterator pointing to the first element, and end() provides an iterator pointing to one past the last element.
  3. Iterate through the list: The for loop iterates from begin() to end(), accessing and printing each element using the dereference operator (*it).

Output:

List elements: 10 20 30 40 50

Example 2: Modifying Elements Using std::list::end

This example demonstrates how to modify elements of a std::list using iterators:

</>
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 (auto it = myList.begin(); it != myList.end(); ++it) {
        std::cout << *it << " ";
    }
    std::cout << std::endl;

    return 0;
}

Explanation:

  1. Define a list: A std::list named myList is initialized with elements {1, 2, 3, 4, 5}.
  2. Get an iterator: The begin() function provides an iterator pointing to the first element.
  3. Modify an element: The first element is modified by dereferencing the iterator and assigning a new value (10).
  4. Print modified list: The list is traversed using begin() and end(), and the modified elements are printed.

Output:

Modified list: 10 2 3 4 5