How can I rewrite function add to be more efficient?

closed account (26q2b7Xj)
Write your question here.
Is there a faster way to accomplish this? It's fine if the vector is small but not as much when it gets larger.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
  class school
	{
	public:
		void add(const std::string& name, const int grade);

		std::vector<std::string> grade(const int grade) const;

		const std::map<int, std::vector<std::string>>& roster() const;

	private:
		std::map<int, std::vector<std::string>> students;
	};

  void school::add(const std::string& name, const int grade)
	{
		students[grade].push_back(name);

		std::sort(students[grade].begin(), students[grade].end());
	}
One way is to store the students as a set:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
  class school
	{
	public:
		void add(const std::string& name, const int grade);
		std::set<std::string> grade(const int grade) const;
		const std::map<int, std::set<std::string>>& roster() const;

	private:
		std::map<int, std::set<std::string>> students;
	};

  void school::add(const std::string& name, const int grade)
	{
		students[grade].insert(name);
	}


Another is to delay sorting until grade() or roster() is called.

A third is to not sort it at all and let the caller sort if they need to. After all, why should class school assume that the caller needs the data sorted?
Last edited on
If the standard comparison for std::set isn't what is required, then an alternative comparison function can be provided. If the data is required sorted in different ways which are pre-known, then different std::set can be used for each required sort order.

not as much when it gets larger


What numbers are we talking about here?
Topic archived. No new replies allowed.