fork download
  1. #include <iostream>
  2. #include <string>
  3. #include <vector>
  4. #include <memory>
  5. #include <algorithm>
  6.  
  7. class Student {
  8. private:
  9. std::string name;
  10.  
  11. public:
  12. Student(const std::string& name_) : name(name_) {}
  13. const std::string& getName() const { return name; }
  14. };
  15.  
  16. class Class {
  17. private:
  18. typedef std::vector<std::shared_ptr<Student>> SubscriptionList;
  19. SubscriptionList students;
  20. const unsigned int MaxSubscribers;
  21.  
  22. public:
  23. Class(unsigned int maxSubscribers) : MaxSubscribers(maxSubscribers) {}
  24.  
  25. bool subscribe(std::shared_ptr<Student>& student) {
  26. if(students.size() >= MaxSubscribers) {
  27. return false; // Class is full, can't subscribe
  28. }
  29.  
  30. // May be put additional checks here, to prevent multiple subscrptions
  31. students.push_back(student);
  32. return true; // Sucessfully subscribed the class
  33. }
  34.  
  35. void unsubscribe(std::shared_ptr<Student>& student) {
  36. SubscriptionList::iterator it = students.begin();
  37. for(;it != students.end();++it) {
  38. if(it->get() == student.get()) {
  39. break;
  40. }
  41. }
  42. students.erase(it);
  43. }
  44.  
  45. void showSubscribedStudents(std::ostream& os) {
  46. unsigned int i = 1;
  47. for(SubscriptionList::iterator it = students.begin();
  48. it != students.end();
  49. ++it, ++i) {
  50. os << i << ". " << (*it)->getName() << std::endl;
  51. }
  52. }
  53. };
  54.  
  55. int main()
  56. {
  57. unsigned int amount;
  58. std::cin >> amount;
  59. std::cin.ignore(1,'\n');
  60.  
  61. Class theClass(amount);
  62.  
  63. for(unsigned int i = 0; i <= amount; ++i)
  64. {
  65. std::string name;
  66. std::getline(std::cin,name);
  67. std::shared_ptr<Student> student(new Student(name));
  68. theClass.subscribe(student);
  69. }
  70.  
  71. theClass.showSubscribedStudents(std::cout);
  72. }
  73.  
  74.  
Success #stdin #stdout 0s 3436KB
stdin
5
John Doe
Jane Doe
Aldo Willis
Chuck Norris
Mia Miles
stdout
1. John Doe
2. Jane Doe
3. Aldo Willis
4. Chuck Norris
5. Mia Miles