C++ Deque::begin() Function



The C++ std::deque::begin() function is used to return an iterator pointing to the first element of the deque. This iterator can be used to traverse the deque from the beginning. It is commonly used in conjuction with other iterator functions like end().

For const deque, begin() function returns an const_iterator, ensuring the elements pointed by the iterator can't be modified.

Syntax

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

iterator begin() noexcept;
const_iterator begin() const noexcept;

Parameters

It does not accept any parameters.

Return value

This function returns an iterator to the beginning of the sequenece container.

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 the begin() function.

#include <iostream>
#include <deque>
int main()
{
    std::deque<char> x = {'A', 'B', 'C', 'D'};
    std::deque<char>::iterator a = x.begin();
    std::cout << "First Element : " << *a << std::endl;
    return 0;
}

Output

Output of the above code is as follows −

First Element : A

Example

Consider the following example, where we are going to modify the first element.

#include <iostream>
#include <deque>
int main()
{
    std::deque<char> x = {'Y', 'B', 'C', 'D'};
    std::deque<char>::iterator y = x.begin();
    *y = 'A';
    for (char elem : x) {
        std::cout << elem << " ";
    }
    return 0;
}

Output

Following is the output of the above code −

A B C D

Example

Let's look at the following example, where we are going to insert elements at the beginning.

#include <iostream>
#include <deque>
int main()
{
    std::deque<int> a = {333,4444};
    a.insert(a.begin(), 22);
    a.insert(a.begin(), 1);
    for (int elem : a) {
        std::cout << elem << " ";
    }
    return 0;
}

Output

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

1 22 333 4444 

Example

Following is the example, where we are going to erase the firt element.

#include <iostream>
#include <deque>
int main()
{
    std::deque<char> a = {'A', 'B', 'C', 'D'};
    a.erase(a.begin());
    for (char elem : a) {
        std::cout << elem << " ";
    }
    return 0;
}

Output

Let us compile and run the above program, this will produce the following result −

B C D 
deque.htm
Advertisements