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

Rated as one of the most sought after skills in the industry, own the basics of coding with our C++ STL Course and master the very concepts by intense problem-solving.





Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.



Improved By : dkp1903

Article Tags :
C++
Practice Tags :