Introduction

Welcome to today's lesson! We'll be exploring a practical application of C++ sets by managing student enrollments for various courses. Imagine you're running an online course platform and need to handle enrollments, checks, and listings of students in different courses. std::unordered_set would be perfect for this kind of problem since it does not allow duplicates, ensuring that a student can't enroll in the same course more than once!

By the end of this session, you'll be well-versed in using sets for such tasks. Let’s dive in!

Introducing Methods to Implement

Here are the methods we need to implement in our enrollment system:

  • void enroll(const std::string& student, const std::string& course);: This method adds a student to a course. If the student is already enrolled, it does nothing.
  • bool unenroll(const std::string& student, const std::string& course);: This method removes a student from a course. It returns true if the student was enrolled and has now been removed. Otherwise, it returns false. If after unenrolling the student, the course becomes empty (no one is enrolled there), remove the course as well.
  • bool is_enrolled(const std::string& student, const std::string& course);: This method checks if a student is enrolled in a course. It returns true if the student is enrolled and false otherwise.
  • std::vector<std::string> list_students(const std::string& course);: This method returns a list of all students enrolled in a given course. If no students are enrolled, it returns an empty vector.

Let's look at how to implement each of these methods step-by-step.

Step 1: Define the Class

We'll start by defining our class and then add each method one by one.

First, we define our EnrollmentSystem class:

#include <unordered_map>
#include <unordered_set>
#include <string>
#include <vector>

class EnrollmentSystem {
public:
    EnrollmentSystem() = default;

private:
    std::unordered_map<std::string, std::unordered_set<std::string>> enrollments;
};

This code initializes an EnrollmentSystem class with an unordered map named enrollments that maps courses to unordered sets of students.

Step 2: Implement 'enroll' Method

Next, we implement the enroll method:

#include <unordered_map>
#include <unordered_set>
#include <string>
#include <vector>
#include <iostream>

class EnrollmentSystem {
public:
    EnrollmentSystem() = default;

    void enroll(const std::string& student, const std::string& course) {
        enrollments[course].insert(student);
    }

private:
    std::unordered_map<std::string, std::unordered_set<std::string>> enrollments;
};

// Example usage:
int main() {
    EnrollmentSystem es;
    es.enroll("Alice", "Math101");
    return 0;
}

Here, the enroll method uses the insert method to add the student to the set of students for the specified course.

Sign up
Join the 1M+ learners on CodeSignal
Be a part of our community of 1M+ users who develop and demonstrate their skills on CodeSignal