Sets are a type of associative containers in which each element has to be unique, because the value of the element identifies it. The value of the element cannot be modified once it is added to the set, though it is possible to remove and add the modified value of that element.

Important Methods

  • iterator begin() noexcept;
    const_iterator begin() const noexcept;
    Returns an iterator referring to the first element in the set container.
  • void clear() noexcept;
    Removes all elements from the set container (which are destroyed), leaving the container with a size of 0.
  • iterator end() noexcept;
    const_iterator end() const noexcept;
    Returns an iterator referring to the past-the-end element in the set container.
  • const_iterator find (const value_type& val) const;
    iterator find (const value_type& val);
    Searches the container for an element equivalent to val and returns an iterator to it if found, otherwise it returns an iterator to set::end.
  • iterator lower_bound (const value_type& val);
    const_iterator lower_bound (const value_type& val) const;
    Returns an iterator pointing to the first element in the container which is not considered to go before val (i.e., either it is equivalent or goes after).
  • iterator upper_bound (const value_type& val);
    const_iterator upper_bound (const value_type& val) const;
    Returns an iterator pointing to the first element in the container which is considered to go after val.
  • size_type size() const noexcept;
    Returns the number of elements in the set container.

 

Example

#include <iostream> 
#include <set> 
#include <iterator> 

using namespace std; 

int main() 
{ 
  // Empty set container 
  set <int> s1;		 

  // insert elements in random order 
  s1.insert(40);  
  s1.insert(20); 
  
  // only one 50 will be added
  s1.insert(50); 
  s1.insert(50);  
  s1.insert(10); 

  // printing set s1 
  set <int, greater <int> > :: iterator itr; 
  for (itr = s1.begin(); itr != s1.end(); ++itr) 
  { 
    cout << '\t' << *itr; 
  }

  // Find the element
  itr = s1.find(20);
   
  // Assigning the elements from s1 to s2 
  set <int> s2(s1.begin(), s1.end()); 

  // Remove all elements up to 50 in s2 
  s2.erase(s2.begin(), s2.find(50)); 

  // Remove element with value 50 in s2 
  int num; 
  num = s2.erase (50); 

  // Lower bound and upper bound for set s1 
  cout << *s1.lower_bound(40); 
  cout << *s1.upper_bound(40); 

  // Clear the set
  s1.clear();
    
  return 0;
}