Sets - a practical example

Scenario: Unique Usernames for a System

Imagine you are writing a piece of software that requires a unique username for each user. You could use a set to store the usernames. When a new user tries to register, you can quickly check if the username is already taken and enforce uniqueness.

Here's a simple example in C++:

#include <iostream> #include <set> #include <string> using namespace std; // Function prototype bool addUsername(set<string>&, string); int main() { set<string> usernames; // Try to add some usernames addUsername(usernames, "user1"); addUsername(usernames, "user2"); addUsername(usernames, "user1"); // This should fail, as "user1" is already taken // Output the list of usernames cout << "Current usernames in the system:" << endl; for (string user : usernames) { cout << user << endl; } return 0; } // Function implementation bool addUsername(set<string>& usernames, string username) { //The insert method returns a pair, where the second //element is a boolean that is true if the insert was //successful (the username was unique) and false otherwise. auto result = usernames.insert(username); if (!result.second) { cout << "Username '" << username << "' is already taken." << endl; return false; } else { cout << "Username '" << username << "' has been added." << endl; return true; } }

In this example, the addUsername function checks if the username is already in the set. If it is not, it adds the new username; otherwise, it informs that the username is taken. The set automatically ensures that all usernames are unique.

This is a practical use case for a set because:

  • You need to ensure that each element (username) is unique.

  • You want to have quick lookups to check if an element already exists in the set.

2024 - Programming 3 / Data Structures - Author: Dr. Kevin Roark