Demo Sets Container
// main.cpp
// SetsDemo
// Created by Kevin Roark
#include <iostream> // Include the I/O stream library for input and output
#include <set> // Include the set container library
using namespace std; // Use the standard namespace to avoid typing "std::" before common functions
int main() {
set<int> mySet; // Declare a set to store integers
set<string> strSet; //Declare a set to store strings
// Insert elements into the set. Duplicate elements will not be added.
mySet.insert(5);
mySet.insert(3);
mySet.insert(8);
mySet.insert(1);
mySet.insert(4);
mySet.insert(7);
mySet.insert(1); // This will not be added to the set as 1 is already present
mySet.insert(10);
//insert some strings
strSet.insert("John");
strSet.insert("Sally");
strSet.insert("Fred");
strSet.insert("Barney");
// Output the size of the set
cout << "Set size: " << mySet.size() << endl;
// Output all the elements in the set
// The elements will be in sorted order as that is how set stores them
cout << "Set elements: ";
for (int x : mySet) {
cout << x << " ";
}
cout << endl;
// Check if the element '7' is present in the set
if (mySet.find(7) != mySet.end()) {
cout << "7 is in the set" << endl;
}
// Erase the element '4' from the set
mySet.erase(4);
// Output the size of the set after erasing an element
cout << "Set size after erasing 4: " << mySet.size() << endl;
// Output all the elements in the set after erasing an element
cout << "Set elements after erasing 4: ";
for (int x : mySet) {
cout << x << " ";
}
cout << endl;
cout << "Now lets look at our string set: " << endl;
for (string str : strSet) {
cout << str << endl;
}
cout << endl;
cout << "Erasing John" << endl;
strSet.erase("John");
for (string str : strSet) {
cout << str << endl;
}
return 0; // Return 0 to indicate successful completion
}
2024 - Programming 3 / Data Structures - Author: Dr. Kevin Roark