deque cbegin() in C++ STL

The cbegin() method in deque is a function in C++ STL which returns an iterator pointing to the first element of the container.

Syntax:

deque_name.cbegin()

Return value: It returns a constant iterator pointing to the first element of the deque. This means, that the iterator can be used to traverse the queue, but not to modify it. That is, functions like insert, erase would throw an error if called using a constant iterator.
The constant iterator should be used when you want no part of your code to modify the contents of the deque.



The following programs illustrates the function.

Program 1:

filter_none

edit
close

play_arrow

link
brightness_4
code

#include <deque>
#include <iostream>
  
using namespace std;
  
int main()
{
  
    // Create a deque
    deque<int> dq = { 2, 5, 7, 8, 6 };
  
    // Print the first element of deque
    // using cbegin() method
    cout << "First element of the deque is: ";
  
    // Get the iterator pointing to the first element
    // And dereference it
    cout << *dq.cbegin();
}

chevron_right


Output:

First element of the deque is: 2

Program 2:

filter_none

edit
close

play_arrow

link
brightness_4
code

#include <deque>
#include <iostream>
  
using namespace std;
  
int main()
{
  
    // Create a deque
    deque<int> dq = { 1, 5, 2, 4, 7 };
  
    // Insert an element at the front
    dq.push_front(45);
  
    // Insert an element at the back
    dq.push_back(56);
  
    // Print the first element of deque
    // using cbegin() method
    cout << "First element of the deque is: ";
  
    // Get the iterator pointing to the first element
    // And dereference it
    cout << *dq.cbegin();
}

chevron_right


Output:

First element of the deque is: 45


My Personal Notes arrow_drop_up

Recommended Posts:



    Article Tags :
    Practice Tags :


    Be the First to upvote.


    Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.