Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <algorithm>
- #include <execution>
- #include <iostream>
- #include <string>
- #include <string_view>
- #include <vector>
- #include <future>
- #include <iterator>
- using namespace std;
- vector<int> makeBuckets(int max, int numberOfBuckets) {
- int e = max / numberOfBuckets;
- vector<int> b(numberOfBuckets, e);
- fill(b.begin(), b.begin() + (max % numberOfBuckets), e + 1);
- return b;
- }
- template <typename ForwardRange, typename Function>
- void ForEachImpl(ForwardRange& range, Function function) {
- static constexpr int PART_COUNT = 4;
- const auto part_length = range.size() / PART_COUNT;
- auto part_begin = range.begin();
- auto part_end = next(part_begin, part_length);
- vector<future<void>> futures;
- for (
- int i = 0;
- i < PART_COUNT;
- ++i,
- part_begin = part_end,
- part_end = (i == PART_COUNT - 1
- ? range.end()
- : next(part_begin, part_length))
- ) {
- futures.push_back(async([function, part_begin, part_end] { for_each(part_begin, part_end, function); }));
- }
- }
- template <typename ExecutionPolicy, typename ForwardRange, typename Function>
- void ForEach(ExecutionPolicy&&, ForwardRange& range, Function function)
- {
- using category = typename std::iterator_traits<typename ForwardRange::iterator>::iterator_category;
- if constexpr ((false == std::is_same_v<category, std::random_access_iterator_tag>) && (is_same_v<decay_t<ExecutionPolicy>, execution::parallel_policy>)) {
- ForEachImpl(range, function);
- } else {
- for_each(range.begin(), range.end(), function);
- }
- }
- template <typename ForwardRange, typename Function>
- void ForEach(ForwardRange& range, Function function) {
- ForEach(execution::seq, range, function);
- }
- int main() {
- // для итераторов с произвольным доступом тоже должно работать
- vector<string> strings = {"cat", "dog", "code"};
- ForEach(strings, [](string& s) { reverse(s.begin(), s.end()); });
- for (string_view s : strings) {
- cout << s << " ";
- }
- cout << endl;
- // вывод: tac god edoc
- return 0;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement