C++ <list> size Function

C++ container class <list>


sizeIs one of the most commonly used functions in list, used toGet the number of elements in the linked list。

sizeIs a member function of container classes, used to return the number of elements currently contained in the linked list.

Unlike vector, list'ssize()Usually completes in O(1) time.

Word Definitions: sizeMeans "size", indicating the number of elements in the linked list.


Basic syntax and parameters

Syntax format

size_type size() const;

Function description

  • Return Value: returns the number of elements in the linked list (size_type)。

Example

Example 1: Get the size of the linked list

Example

#include <iostream>
#include <list>

int main() {
    std::list<int> empty;
    std::cout << "Empty linked list size: " << empty.size() << std::endl;

    std::list<int> numbers = {1, 2, 3, 4, 5};
    std::cout << 5-element linked list size: << numbers.size() << std::endl;

    numbers.push_back(6);
    std::cout << size after adding: << numbers.size() << std::endl;

    return 0;
}

Expected execution result:

空链表 size: 0
5元素链表 size: 5
添加后 size: 6

C++ container class <list>

other extensions