C++ Deque::size() Function



The C++ std::deque::size() function is used to return the number of elements currently stored in the deque. It retrieves the count of the elements, allowing dynamic size management. Unlike arrays, deques support fast insertion and deletion at both ends.

Syntax

Following is the syntax for std::deque::size() function.

size_type size() const noexcept;

Parameters

It does not accept any parameter.

Return value

It returns the number of elements present in the deque.

Exceptions

This function never throws exception.

Time complexity

The time complexity of this function is constant i.e. O(1)

Example

In the following example, we are going to consider the basic usage of size() function.

#include <iostream>
#include <deque>
int main()
{
    std::deque<char> a = {'A', 'B', 'C', 'D'};
    std::cout << "Size of the deque is: " << a.size() << std::endl;
    return 0;
}

Output

Output of the above code is as follows −

Size of the deque is: 4

Example

Consider the following example, where we are going to get the size of the deque after removing few elements.

#include <iostream>
#include <deque>
int main()
{
    std::deque<int> a = {11,12,23,34,45};
    a.pop_front();
    a.pop_back();
    std::cout << "Size of deque after removing element :  " << a.size() << std::endl;
    return 0;
}

Output

Following is the output of the above code −

Size of deque after removing element :  3

Example

Let's look at the following example, where we are going to apply the size() function to the deque in its initial stage and after clearing the deque.

#include <iostream>
#include <deque>
int main()
{
    std::deque<char> x = {'A', 'B', 'C', 'D'};
    std::cout << "Initial size: " << x.size() << std::endl;
    x.clear();
    std::cout << "Size after clearing : " << x.size() << std::endl;
    return 0;
}

Output

If we run the above code it will generate the following output −

Initial size: 4
Size after clearing : 0
deque.htm
Advertisements