Sets in C++
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.
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 setset<string> Fruits;// using insert method to add elements to the setFruits.insert("Apple");Fruits.insert("Banana");Fruits.insert("Kiwi");// using begin and end to iterate through the setcout << "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 setFruits.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 setcout << "Fruits has " << Fruits.size() << " elements" << endl;cout << endl;// clearing the setFruits.clear();cout << "Fruits now has " << Fruits.size() << " elements" << endl;return 0;}
Free Resources