Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

sets
c++
containers

Sets in C++

Educative Answers Team

Sets are associative containers that store unique elements. A stored element must be unique because it is identified with the value itself. Once the elements are inserted in the set, they cannot be modified; however, they can be inserted or removed from the container.

svg viewer

Set methods

Below are some of the basic methods associated with sets:

  • begin() returns an iterator to the first element in a set.

  • end() returns an iterator to the “theoretical” element that is after the last element in a set.

  • insert(const val) adds a new element (val) to a set.

  • erase(const val) removes the element (val) from a set.

  • clear() removes all the elements from a set.

  • size() returns the number of elements in a​ set.

Code

The code snippet below illustrates how the functions above are used​:

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

int main() {
  // Declaring a set
  set<string> Fruits;

  // using insert method to add elements to the set
  Fruits.insert("Apple");
  Fruits.insert("Banana");
  Fruits.insert("Kiwi");

  // using begin and end to iterate through the set
  cout << "Elements of the set:       ";
  for(std::set<string>::iterator i = Fruits.begin(); i != Fruits.end(); i++)
  {
    cout << *i << ", ";
  }
  cout << endl;
  cout << endl;


  // using remove method to remove elemets from the set
  Fruits.erase("Apple");

  cout << "After removing Apple:   ";
  for(std::set<string>::iterator i = Fruits.begin(); i != Fruits.end(); i++)
  {
    cout << *i << ", ";
  }
  cout << endl;
  cout << endl;


  // Checking for number eof elements in the set
  cout << "Fruits has " << Fruits.size() << " elements" << endl;

  cout << endl;

  // clearing the set
  Fruits.clear();

  cout << "Fruits now has " << Fruits.size() << " elements" << endl;

  return 0;
}
svg viewer

RELATED TAGS

sets
c++
containers
Copyright ©2022 Educative, Inc. All rights reserved
RELATED COURSES

View all Courses

Keep Exploring