Last active
February 15, 2019 14:56
-
-
Save LostInKadath/e92d43356efa85d11c4e4ea60fbb2b28 to your computer and use it in GitHub Desktop.
Отсортировать числа по возрастанию суммы составляющих цифр
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <iostream> | |
#include <vector> | |
#include <algorithm> | |
#include <functional> | |
using std::cout; | |
using std::vector; | |
template <typename ContainerT, bool stable = false> | |
class digsum_sort | |
{ | |
using ValueType = typename ContainerT::value_type; | |
using IteratorType = typename ContainerT::iterator; | |
using ComparatorType = std::function<bool(ValueType, ValueType)>; | |
using SortFuncType = std::function<void(IteratorType, IteratorType, ComparatorType)>; | |
public: | |
digsum_sort() | |
{ | |
cmp_func = [](ValueType a, ValueType b) | |
{ | |
std::div_t div; | |
int sum_a = 0, sum_b = 0; | |
for (div.quot = a; div.quot > 0; sum_a += div.rem) { div = std::div(div.quot, 10); } | |
for (div.quot = b; div.quot > 0; sum_b += div.rem) { div = std::div(div.quot, 10); } | |
return sum_a < sum_b; | |
}; | |
sort_func = stable | |
? std::stable_sort<IteratorType, ComparatorType> | |
: std::sort<IteratorType, ComparatorType>; | |
} | |
void operator()(ContainerT &arr) | |
{ | |
sort_func(std::begin(arr), std::end(arr), cmp_func); | |
} | |
private: | |
ComparatorType cmp_func; | |
SortFuncType sort_func; | |
}; | |
void show_array(const vector<int> &arr) | |
{ | |
cout << "{ "; | |
for (int a : arr) { | |
cout << a << " "; | |
} | |
cout << "}\n"; | |
} | |
int main() | |
{ | |
vector<int> arr; | |
arr = { 19, 22, 30 }; | |
show_array(arr); | |
digsum_sort<vector<int>, false>()(arr); | |
cout << "-->\n"; | |
show_array(arr); | |
cout << "\n"; | |
arr = { 25, 123, 6000, 11111, 77, 30, 999, 1000000 }; | |
show_array(arr); | |
digsum_sort<vector<int>, true>()(arr); | |
cout << "-->\n"; | |
show_array(arr); | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment