Komparator studenata

Neka je data struktura student definisana na sledeći način:

struct student {
    std::string name;
    int age;
    double gpa;
};

Definisati tri komparatora za strukturu student:

Test

#include <iostream>
#include <vector>
#include <string>
#include <algorithm>

namespace matf {

	struct student {
		std::string name;
		int age;
		double gpa;
	};

	// Ovde idu vase implementacije

} // namespace matf

int main(void)
{
	std::vector<matf::student> students = {
		{"Marko", 21, 8.5},
		{"Ana", 22, 9.1},
		{"Jovan", 20, 7.8}
	};

	std::sort(students.begin(), students.end(), matf::comparator_by_name());
	std::cout << "Sorted by name:\n";
	for (const auto &s : students) {
		std::cout << s.name << ", " << s.age << ", " << s.gpa << "\n";
	}

	std::sort(students.begin(), students.end(), matf::comparator_by_age());
	std::cout << "\nSorted by age:\n";
	for (const auto &s : students) {
		std::cout << s.name << ", " << s.age << ", " << s.gpa << "\n";
	}	

	std::sort(students.begin(), students.end(), matf::comparator_by_gpa());
	std::cout << "\nSorted by GPA:\n";
	for (const auto &s : students) {
		std::cout << s.name << ", " << s.age << ", " << s.gpa << "\n";
	}	

	return 0;
}

Rešenje

main.cpp

#include <iostream>
#include <vector>
#include <string>
#include <algorithm>

namespace matf {

	struct student {
		std::string name;
		int age;
		double gpa;
	};

	struct comparator_by_name {
		bool operator()(const student &a, const student &b) const
		{
			return a.name < b.name;
		}
	};

	struct comparator_by_age {
		bool operator()(const student &a, const student &b) const
		{
			return a.age < b.age;
		}
	};

	struct comparator_by_gpa {
		bool operator()(const student &a, const student &b) const
		{
			return a.gpa > b.gpa;
		}
	};

} // namespace matf

int main(void)
{
	std::vector<matf::student> students = {
		{"Marko", 21, 8.5},
		{"Ana", 22, 9.1},
		{"Jovan", 20, 7.8}
	};

	std::sort(students.begin(), students.end(), matf::comparator_by_name());
	std::cout << "Sorted by name:\n";
	for (const auto &s : students) {
		std::cout << s.name << ", " << s.age << ", " << s.gpa << "\n";
	}

	std::sort(students.begin(), students.end(), matf::comparator_by_age());
	std::cout << "\nSorted by age:\n";
	for (const auto &s : students) {
		std::cout << s.name << ", " << s.age << ", " << s.gpa << "\n";
	}	

	std::sort(students.begin(), students.end(), matf::comparator_by_gpa());
	std::cout << "\nSorted by GPA:\n";
	for (const auto &s : students) {
		std::cout << s.name << ", " << s.age << ", " << s.gpa << "\n";
	}	

	return 0;
}