Skip to content

Grade School

Intro

In the end, you should be able to:

  • Add a student's name to the roster for a grade
  • "Add Jim to grade 2."
  • "OK."
  • Get a list of all students enrolled in a grade
  • "Which students are in grade 2?"
  • "We've only got Jim just now."
  • Get a sorted list of all students in all grades. Grades should sort as 1, 2, 3, etc., and students within a grade should be sorted alphabetically by name.
  • "Who all is enrolled in school right now?"
  • "Grade 1: Anna, Barb, and Charlie. Grade 2: Alex, Peter, and Zoe. Grade 3…"

Note that all our students only have one name. (It's a small town, what do you want?)

Task

Given students' names along with the grade that they are in, create a roster for the school.

The Code

 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
#include "grade_school.h"
#include <algorithm>
#include <string>
#include <utility>
#include <vector>

namespace grade_school {
void school::add(std::string nama, int kelas) {
std::vector<std::string> tmp = murid[kelas];
tmp.push_back(nama);
std::sort(tmp.begin(), tmp.end());
murid[kelas] = tmp;
}

std::map<int, std::vector<std::string>> school::roster() const { return murid; }

std::vector<std::string> school::grade(int kelas) const {

std::vector<std::string> tmp{};
if (murid.count(kelas) <= 0)
    return tmp;
tmp = murid.at(kelas);
return tmp;
}
} // namespace grade_school
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
#include <string>
#include <vector>
#if !defined(GRADE_SCHOOL_H)
#define GRADE_SCHOOL_H
#include "map"
#include "string"
#include "vector"

namespace grade_school {
class school {
public:
std::map<int, std::vector<std::string>> murid{};
void add(std::string, int);
std::map<int, std::vector<std::string>> roster() const;
std::vector<std::string> grade(int) const;
};
} // namespace grade_school

#endif // GRADE_SCHOOL_H 

Last update: February 13, 2021

Comments