C++ std::list::size

The std::list::size function returns the number of elements currently stored in the list. It provides an efficient way to determine the size of the list container. This function is often used in scenarios where the list’s element count is required for iteration or conditional checks.


Syntax of std::list::size

</>
Copy
size_type size() const noexcept;

Parameters

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

Return Value

Returns the number of elements in the list as a value of type size_type, which is typically an unsigned integer.

Exceptions

The std::list::size function does not throw exceptions as it is marked noexcept. It is a safe operation that simply returns the number of elements currently stored in the list.


Examples for std::list::size

Example 1: Getting the Size of a List

This example demonstrates how to use the size() function to get the number of elements in a list:

</>
Copy
#include <iostream>
#include <list>

int main() {
    std::list<int> myList = {10, 20, 30, 40, 50};

    std::cout << "The size of the list is: " << myList.size() << std::endl;

    return 0;
}

Explanation:

  1. Define a list: A std::list named myList is initialized with elements {10, 20, 30, 40, 50}.
  2. Get the size: The size() function is called on myList to determine the number of elements in the list. It returns 5 in this case.
  3. Print the size: The result is printed to the console.

Output:

The size of the list is: 5

Example 2: Using std::list::size to Control Iteration

This example demonstrates how the size() function can be used to control iteration:

</>
Copy
#include <iostream>
#include <list>

int main() {
    std::list<int> myList = {1, 2, 3};

    std::cout << "List elements: ";
    if (myList.size() > 0) {
        for (auto it = myList.begin(); it != myList.end(); ++it) {
            std::cout << *it << " ";
        }
    } else {
        std::cout << "The list is empty.";
    }
    std::cout << std::endl;

    return 0;
}

Explanation:

  1. Define a list: A std::list named myList is initialized with elements {1, 2, 3}.
  2. Check the size: The size() function is called to determine if the list is empty. If the size is greater than zero, the program iterates over the elements.
  3. Iterate through the list: A for loop iterates from begin() to end() to print each element of the list.
  4. Handle empty lists: If the list is empty, a message indicating this is printed.

Output:

List elements: 1 2 3