C++ Standard Library C++ STL Library

C++ unordered_multiset - cbegin() Function



The C++ unordered_multiset::cbegin function returns the constant iterator (const_iterator) pointing to the first element of the unordered_multiset 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 multiset element is not itself constant.

Note: There is no guarantee of a specific element to be considered as the first element of the unordered_multiset (or the bucket). But the range that goes from begin to end contains all elements of the unordered_multiset 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_multiset container or one of its bucket.

Time Complexity

Constant i.e, Θ(1)

Example:

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

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

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

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

The output of the above code will be:

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

The uMSet's bucket contains: 
The bucket #0 contains: -500 55 55 
The bucket #1 contains: 45 
The bucket #2 contains: 24 
The bucket #3 contains: 25 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