Private archive copy · Unofficial site · Content copyright belongs to Runoob Tutorial and the original authors · View Original

C++ size() function

C++ size() function

C++ Container Class The C++ container class


size is one of the most commonly used and fundamental functions in array, used toget the number of elements in the container.

size is a member function of the container class, used toreturns the current number of elements in the container. Unlike vector, array's size is fixed and determined at compile time.

size is the most frequently used function when operating on array, used in scenarios such as loop traversal and bounds checking.

Word meaning: size means 'size', i.e., the number of elements in the container.


Basic syntax and parameters

size is a member function of the container class; calling it requires no parameters.

Syntax format


constexpr size_type size() const noexcept;

Parameter Description

- `size` takes no arguments.

Function description


Example

Let us thoroughly master size through a series of examples from simple to complex.

Example 1: Basic usage - getting the number of elements

Example

#include

#include

int

main

(

)

{

   

// Arrays of different sizes

    std

::

array

<
int
,
3
small
=
{
1
,
2
,
3
}

;

    std

::

array

<
int
,
5
medium
=
{
1
,
2
,
3
,
4
,
5
}

;

    std

::

array

<
int
,
10
large
=
{
}

;

    std

::

cout

<<

"small array size: "

<<

small.

size

(

)

<<

std

::

endl

;

    std

::

cout

<<

"medium array size: "

<<

medium.

size

(

)

<<

std

::

endl

;

    std

::

cout

<<

"large array size: "

<<

large.

size

(

)

<<

std

::

endl

;

   

return

0

;

}

Expected output:

small array 大小: 3
medium array 大小: 5
large array 大小: 10

Code analysis:

  1. array's size is determined at compile time and specified by the template parameter.
  2. size() returns exactly this compile-time-determined value.

Example 2: Using size() in a loop

size() is most commonly used to control loop traversal.

Example

#include

#include

int

main

(

)

{

    std

::

array

<
int
,
5
numbers
=
{
10
,
20
,
30
,
40
,
50
}

;

   

// Use size() to control the loop

    std

::

cout

<<

"Traverse all elements: "

;

   

for

(

size_t

i

=

0

;

i

<

numbers.

size

(

)

;

++

i

)

{

        std

::

cout

<<

numbers

[

i

]

<<

" "

;

   

}

    std

::

cout

<<

std

::

endl

;

   

// Use size() to get the boundary for reverse traversal

    std

::

cout

<<

"Reverse traversal: "

;

   

for

(

size_t

i

=

numbers.

size

(

)

;

i

0

;

--

i

)

{

        std

::

cout

<<

numbers

[

i

1

]

<<

" "

;

   

}

    std

::

cout

<<

std

::

endl

;

   

return

0

;

}

Expected output:

遍历所有元素: 10 20 30 40 50
反向遍历: 50 40 30 20 10

Code analysis: