C++ multiset Library - begin() Function



Description

The multiset::begin() function in C++ STL returns an iterator pointing to the first element in the multiset container. It does not accept any parameter.

An iterator is an object that points to an element in the container. It is used to traverse the elements in the container.

Syntax

Following are the ways in which multiset::begin works in various C++ versions −

iterator begin(); //C++98
iterator begin() noexcept; //C++11 onwards

Return value

It returns an iterator pointing to the first element in the multiset container.

Exceptions

It never throws exceptions.

Time complexity

Time complexity is constant.

Examples of multiset::begin() Function

The following example demonstrates the usage of multiset::begin() function.

Printing Elements of multiset

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

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

int main(){
   int myints[] = {50, 40, 20, 30, 20, 10};
   int n = sizeof(myints) / sizeof(myints[0]);

   multiset<int> mymultiset(myints, myints + n);
   cout << "Multiset elements:";
   multiset<int>::iterator it = mymultiset.begin();
   for (; it != mymultiset.end(); ++it){
      cout << *it << " ";
   }
   cout << '\n';

   return 0;
}

The output of the above code is given below −

Multiset elements:10 20 20 30 40 50

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 begin() 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>::iterator it = mymultiset.begin();
   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 begin() iterator. Since, elements in the multiset are always const, it will give a compilation error

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

int main() {
   multiset<int> numbers = {3, 1, 2};
   auto it = numbers.begin();
   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:10:9: error: assignment of read-only location 'it.std::_Rb_tree_const_iterator::operator*()'
   10 |     *it = 10; // It will give a compilation error
      |     ~~~~^~~~
multiset.htm
Advertisements