C++ multiset Library - end() Function



Description

The multiset::end() function in C++ STL returns an iterator that points to element past the end in the multiset container. It does not accept any parameter.

The past the end element represents the element after the last element in the multiset. It is just a theoretical value and does not point to any element.

Syntax

Following are the ways in which multiset::end() works in various C++ versions −

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

Return value

It returns an iterator that points to element past the end in the multiset container.

Exceptions

It never throws exceptions.

Time complexity

Time complexity is constant.

Examples of multiset::end() Function

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

Accessing Last Element of multiset

The following example accesses the last element in the multiset. The end() function points to element past the last element. Here, we have used --last to move the pointer to the last element of multiset.

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

int main(){
   multiset<string> words = {"banana", "apple", "cherry", "apple"};
   multiset<string>::iterator last = words.end(); // Pointing beyond last element
   --last; // Moving the pointer to last element
   cout << "Last element in multiset: " << *last << endl;

   return 0;
}

The output of the above code is as follows −

Last element in multiset: cherry

Reverse Iteration Using end() Function

In this example, we have used the end() function to iterate the multiset elements in the reverse order −

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

int main(){
   multiset<int> values = {1, 3, 2, 4, 3};

   cout << "Multiset elements in reverse order:\n";
   for (multiset<int>::iterator it = --values.end();; --it) {
      cout << *it << " ";
         if (it == values.begin())
      break;
   }

   return 0;
}

The output of the above code is as follows −

Multiset elements in reverse order:
4 3 3 2 1

Checking If multiset Is Empty

In this example, we have an empty multiset. To check if this multiset is empty or not, we compare the iterators returned using the begin() and end() function respectively. If both the iterators point to same point, then the multiset is empty.

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

int main(){
   multiset<int> nums;

   if (nums.begin() == nums.end()){
      cout << "Multiset is empty.\n";
   } else {
      cout << "Multiset is not empty.\n";
   }

   return 0;
}

The output of the above code is as follows −

Multiset is empty.
multiset.htm
Advertisements