C++ multiset Library - cend() Function



Description

The multiset::cend() function in C++ STL returns a constant iterator that points to element past the end 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.

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 is the way in which multiset::cend() works in C++11 and later versions:

const_iterator cend() const noexcept;

Return value

It returns a constant iterator that points to element past the end of the multiset container.

Exceptions

It never throws exceptions.

Time complexity

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

Examples of multiset::cend() Function

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

Accessing Last Element of multiset

The following example accesses the last element in the multiset. The cend() 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>::const_iterator last = words.cend(); // 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 cend() Function

In this example, we have used the cend() 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>::const_iterator it = --values.cend();; --it){
      cout << *it << " ";
      if (it == values.cbegin())
         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 cbegin() and cend() functions 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.cbegin() == nums.cend()){
      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