C++ Standard Library C++ STL Library

C++ unordered_set - cbegin() Function



The C++ unordered_set::cbegin function returns the constant iterator (const_iterator) pointing to the first element of the unordered_set container or one of its bucket.

C++ cbegin cend

Note: A const_iterator is an iterator that points to constant value. The difference between iterator and const_iterator is that the const_iterator cannot be used to modify the content it points to, even if the set element is not itself constant.

Note: There is no guarantee of a specific element to be considered as the first element of the unordered_set (or the bucket). But the range that goes from begin to end contains all elements of the unordered_set container (or the bucket).

Syntax

//container iterator
const_iterator cbegin() const noexcept;

//bucket iterator
const_local_iterator cbegin ( size_type n ) const;

Parameters

n Specify the bucket number. It should be lower than the bucket_count.

Return Value

A const_iterator to the beginning of the unordered_set container or one of its bucket.

Time Complexity

Constant i.e, Θ(1)

Example:

In the example below, the unordered_set::cbegin function returns the const_iterator pointing to the first element of the unordered_set container or one of its bucket. The unordered_set::cbegin function is often used with unordered_set::cend function to specify a range including all elements of the unordered_set container or one of its bucket.

#include <iostream>
#include <unordered_set>
using namespace std;
 
int main (){
  unordered_set<int> uSet{55, 25, 128, 5, 72, -500, 45, 24, -20};

  cout<<"The uSet contains: ";
  for(auto cit = uSet.cbegin(); cit != uSet.cend(); ++cit)
    cout<<*cit<<" ";

  cout<<"\n\nThe uSet's bucket contains: ";
  for(unsigned int i = 0; i < uSet.bucket_count(); i++) {
    cout<<"\nThe bucket #"<<i<<" contains: ";   
    for(auto cit = uSet.cbegin(i); cit != uSet.cend(i); ++cit) {
      cout<<*cit<<" ";
    } 
  } 
  return 0;
}

The output of the above code will be:

The uSet contains: 24 45 72 5 -20 128 25 -500 55 

The uSet's bucket contains: 
The bucket #0 contains: -500 55 
The bucket #1 contains: 45 
The bucket #2 contains: 24 
The bucket #3 contains: 25 
The bucket #4 contains: 
The bucket #5 contains: 5 
The bucket #6 contains: 72 
The bucket #7 contains: -20 128 
The bucket #8 contains: 
The bucket #9 contains: 
The bucket #10 contains: 

❮ C++ <unordered_set> Library