C++ multiset Library - cbegin() Function



Description

The multiset::cbegin() function in C++ STL returns a constant iterator pointing to the first element in the multiset container. It does not accept any parameters. The returned constant iterator cannot be used for modifying elements in the container. It is just used to traverse the elements.

Syntax

Following is syntax of multiset::cbegin() function −

const_iterator cbegin() const noexcept; 

Return value

It returns a const_iterator pointing to the first element in the multiset container.

Exceptions

It never throws exceptions.

Time complexity

The time complexity of multiset::cbegin() function is constant.

Examples of multiset::cbegin() Function

The following examples demonstrate the usage of multiset::cbegin() function.

Using cbegin() with const multiset

In this example, we are using cbegin() iterator to print all the elements present in the const multiset container. The cbegin() iterator is used to get the first element of the multiset as a constant iterator.

#include <iostream>
#include <set>
using namespace std;

void print(const multiset<int> &nums){
   cout << "Elements in the const multiset:\n";
   for (auto it = nums.cbegin(); it != nums.cend(); ++it){
      cout << *it << " ";
   }
   cout << "\n";
}

int main(){
   const multiset<int> data = {5, 1, 3, 3, 7};
   print(data);

   return 0;
}

The output of the above code is given below −

Elements in the const multiset:
1 3 3 5 7

Accessing First Element of multiset

The following example accesses the first element present in the multiset. We input the elements in any order, but multiset automatically arranges the elements in ascending order, and cbegin() iterator returns the first element in the sorted container.

#include <iostream>
#include <set>
using namespace std;
int main(){
   int myints[] = {75, 23, 65, 42, 13};
   int n = sizeof(myints) / sizeof(myints[0]);
   multiset<int> mymultiset(myints, myints + n);
   multiset<int>::const_iterator it = mymultiset.cbegin();
   cout << "The first element is: " << *it << endl;
   return 0;
}

The output of the above code is given below −

The first element is: 13

Modifying First Element of multiset

In this example, we are trying to modify the value of first element in the multiset using the cbegin() iterator. Since, cbegin() returns a const_iterator, it will give a compilation error

#include <iostream>
#include <set>
using namespace std;
int main(){
   multiset<int> numbers = {3, 1, 2};
   auto it = numbers.cbegin();
   cout << "Modifying the first element:\n";
   *it = 10; // It will give a compilation error
   cout << "First element is: " << *it << endl;
   return 0;
}

The output of the above code is given below −

main.cpp: In function 'int main()':
main.cpp:9:9: error: assignment of read-only location 
    'it.std::_Rb_tree_const_iterator::operator*()'
    9 |     *it = 10; // It will give a compilation error
      |     ~~~~^~~~
multiset.htm
Advertisements