1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 |
#include <iostream> #include <unordered_map> #include <string> class Student { public: Student(const std::string& name, int age) : name(name), age(age) {} void display() const { std::cout << "Name: " << name << ", Age: " << age << std::endl; } private: std::string name; int age; }; class StudentDatabase { public: void addStudent(const std::string& id, const std::string& name, int age) { if (students.find(id) == students.end()) { students[id] = Student(name, age); std::cout << "Student added: " << name << std::endl; } else { std::cout << "Student ID already exists!" << std::endl; } } void viewStudent(const std::string& id) const { if (students.find(id) != students.end()) { students.at(id).display(); } else { std::cout << "Student ID not found!" << std::endl; } } void deleteStudent(const std::string& id) { if (students.find(id) != students.end()) { students.erase(id); std::cout << "Student ID " << id << " deleted." << std::endl; } else { std::cout << "Student ID not found!" << std::endl; } } private: std::unordered_map<std::string, Student> students; }; int main() { StudentDatabase db; // Adding students db.addStudent("1001", "Alice Johnson", 20); db.addStudent("1002", "Bob Smith", 22); // Viewing student details db.viewStudent("1001"); db.viewStudent("1002"); // Deleting a student db.deleteStudent("1001"); // Attempting to view deleted student db.viewStudent("1001"); return 0; } |
Explanation:
- Student Class:
- Represents a student with
name
andage
. display() const
: Displays the student’s details.
- Represents a student with
- StudentDatabase Class:
- Manages student records using an unordered map (
std::unordered_map
). addStudent(const std::string& id, const std::string& name, int age)
: Adds a new student if the ID does not already exist.viewStudent(const std::string& id) const
: Displays the details of a student based on their ID.deleteStudent(const std::string& id)
: Deletes a student record by ID if it exists.
- Manages student records using an unordered map (
- main Function:
- Demonstrates adding students, viewing their details, deleting a student, and attempting to view the details of a deleted student.
Compilation:
To compile the program, use:
1 |
g++ student_database.cpp -o student_database |
Run the program with:
1 |
./student_database |