C++ Set Library - erase Function



Description

It removes from the set container either a single element or a range of elements.

Declaration

Following are the ways in which std::set::erase works in various C++ versions.

C++98

void erase (iterator position);

C++11

iterator erase (const_iterator position);

Return value

It returns the number of elements erased.

Exceptions

It never throws exception.

Time complexity

Time complexity is constant.

Example

The following example shows the usage of std::set::erase.

#include <iostream>
#include <set>

int main () {
   std::set<int> myset;
   std::set<int>::iterator it;

   for (int i = 1; i < 10; i++) myset.insert(i*20);  

   it = myset.begin();
   ++it;                                        

   myset.erase (it);

   myset.erase (80);

   it = myset.find (60);
   myset.erase (it, myset.end());

   std::cout << "myset contains:";
   for (it = myset.begin(); it!=myset.end(); ++it)
      std::cout << ' ' << *it;
   std::cout << '\n';

   return 0;
}

The above program will compile and execute properly.

myset contains: 20 
set.htm
Advertisements