In C++, std::list::size() returns the number of elements that a std::list holds right now. An empty list has size 0.
The value changes when you add or remove elements. Since C++11 the list keeps the count, so size() is fast. Include <list> to use it.
This is a member of std::list<T>, a doubly linked list. Every element lives in its own node with a link to the previous and the next node, so a list can insert and erase anywhere quickly once you hold an iterator. It has no access by index, so l[i] does not exist.
Syntax
Call size with empty brackets. It returns an unsigned number.
C++
std::size_t n = l.size(); // how many elements
bool has = l.size() > 0;
Call
What it does
l.size()
Returns the count of elements as a size_type, which is an unsigned integer type.
To test for “no elements”, l.empty() is clearer than l.size() == 0.
Library declarations
C++
size_type size() const noexcept;
Parameters
Parameter
Description
None
size() takes no parameters. Call it with empty brackets.
Return Value
Return Value
Description
size_type
The number of elements in the list. It is unsigned, usually std::size_t.
C++ Examples
Example 1 — size() Counts the Elements
Print the size of a list that you create with five zeros.