一:功能
遍历前n个元素
二:用法
#include <vector>
#include <algorithm>
#include <string>
#include <iostream>
#include <execution>
#include <syncstream>constexpr inline size_t MAIN_SEATS = 8;
constexpr inline size_t PAGE_SIZE = 5;struct Player {int score = 0;std::string display_name;
};std::vector<Player> get_rankings() {return {{20, "Player 1"}, {21, "Player 2"}, {23, "Player 3"}, {19, "Player 4"}, {5, "Player 5"},{18, "Player 6"}, {17, "Player 7"}, {25, "Player 8"}, {24, "Player 9"}, {3, "Player 10"},};
}void send_invitation_to_main_tournament(const Player& player) {std::osyncstream(std::cout) << "Inviting " << player.display_name << " to the main tournament.\n";
}void store_final_score(int page, const std::string& name, int score) {std::osyncstream(std::cout) << "Appending to page " << page << " : " << name << " scored " << score << ".\n";
}int main() {std::vector<Player> final_ranking = get_rankings();std::ranges::sort(final_ranking, std::greater<>(), &Player::score);std::for_each_n(std::execution::par_unseq, final_ranking.begin(), std::min(MAIN_SEATS, final_ranking.size()),send_invitation_to_main_tournament);auto it = final_ranking.begin();uint32_t page = 0;while (it != final_ranking.end()) {size_t cnt = std::min(PAGE_SIZE, size_t(final_ranking.end() - it));std::for_each_n(it, cnt, [page](const Player& p) {store_final_score(page, p.display_name, p.score);});page++;it += cnt;}
}
三:实现
#include <algorithm>
#include <iostream>
#include <vector>template<class InputIt, class Size, class UnaryFunction>
InputIt my_for_each_n(InputIt first, Size n, UnaryFunction f)
{for (Size i = 0; i < n; ++first, (void) ++i) {f(*first);}return first;
}int main()
{std::vector<int> ns{1, 2, 3, 4, 5};for (auto n: ns) std::cout << n << ", ";std::cout << '\n';my_for_each_n(ns.begin(), 3, [](auto& n){ return n; });for (auto n: ns) std::cout << n << ", ";std::cout << '\n';
}