Komparator po modulu
Napisati funktor comparator_by_modulus koji prima jedan ceo broj m u konstruktoru, i poredi dva cela broja po njihovom ostatku pri deljenju sa m (rastuće).
Test
#include <iostream>
#include <vector>
#include <algorithm>
namespace matf {
// Ovde ide vasa implementacija
} // namespace matf
int main(void)
{
std::vector<int> numbers = { 10, 22, 35, 47, 53, 64, 78, 89, 91 };
std::sort(
numbers.begin(), numbers.end(),
matf::comparator_by_modulus(10)
);
for (const auto &num : numbers) {
std::cout << num << " "; // Ispisuje: 10 91 22 53 64 35 47 78 89
}
std::cout << std::endl;
return 0;
}Rešenje
main.cpp
#include <iostream>
#include <vector>
#include <algorithm>
namespace matf {
struct comparator_by_modulus {
int modulus;
comparator_by_modulus(int mod) : modulus(mod) {}
bool operator()(int a, int b) const
{
return (a % modulus) < (b % modulus);
}
};
} // namespace matf
int main(void)
{
std::vector<int> numbers = { 10, 22, 35, 47, 53, 64, 78, 89, 91 };
std::sort(
numbers.begin(), numbers.end(),
matf::comparator_by_modulus(10)
);
for (const auto &num : numbers) {
std::cout << num << " "; // Ispisuje: 10 91 22 53 64 35 47 78 89
}
std::cout << std::endl;
return 0;
}