Skip to content
Related Articles

Related Articles

deque cbegin() in C++ STL
  • Difficulty Level : Basic
  • Last Updated : 18 Mar, 2019

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:






#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();
}


Output:

First element of the deque is: 2

Program 2:




#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();
}


Output:

First element of the deque is: 45

Attention reader! Don’t stop learning now. Get hold of all the important C++ Foundation and STL concepts with the C++ Foundation and STL courses at a student-friendly price and become industry ready.

My Personal Notes arrow_drop_up
Recommended Articles
Page :