database.h

Download
c 62 lines 1.7 KB
 1#ifndef DATABASE_H
 2#define DATABASE_H
 3
 4#include "student.h"
 5#include <vector>
 6#include <memory>
 7#include <string>
 8#include <map>
 9
10/**
11 * @brief Custom exception for student not found errors
12 */
13class StudentNotFoundException : public std::exception {
14private:
15    std::string message;
16public:
17    explicit StudentNotFoundException(int id)
18        : message("Student with ID " + std::to_string(id) + " not found") {}
19    explicit StudentNotFoundException(const std::string& name)
20        : message("Student with name '" + name + "' not found") {}
21    const char* what() const noexcept override { return message.c_str(); }
22};
23
24/**
25 * @brief Student database management system
26 *
27 * This class demonstrates:
28 * - Smart pointers (shared_ptr) for memory management
29 * - STL containers (vector, map)
30 * - STL algorithms (find_if, sort, accumulate, count_if)
31 * - File I/O with CSV format
32 * - Exception handling
33 */
34class StudentDatabase {
35private:
36    std::vector<std::shared_ptr<Student>> students;
37
38public:
39    // CRUD operations
40    void addStudent(std::shared_ptr<Student> student);
41    void removeStudent(int id);
42    std::shared_ptr<Student> findById(int id) const;
43    std::vector<std::shared_ptr<Student>> findByName(const std::string& name) const;
44
45    // List and sort operations
46    void listAll() const;
47    void sortById();
48    void sortByName();
49    void sortByGpa();
50
51    // Statistics
52    double calculateAverageGpa() const;
53    std::map<std::string, int> countByMajor() const;
54    size_t size() const { return students.size(); }
55
56    // File I/O
57    void saveToFile(const std::string& filename) const;
58    void loadFromFile(const std::string& filename);
59};
60
61#endif // DATABASE_H