赞
踩
部分排序,即选出前n个最大值或者最小值,并将其保存到另外一个容器中。
- #include <vector>
- #include <algorithm>
- #include <iostream>
- #include <iterator>
-
- int main() {
- std::vector<int> top(3);
-
- auto input = std::istream_iterator<int>(std::cin);
- auto cnt = std::counted_iterator(input, 10);
-
- std::ranges::partial_sort_copy(cnt, std::default_sentinel,
- top.begin(), top.end(),
- std::greater<>{});
- for (auto v : top) {
- std::cout << v << " ";
- }
- std::cout << "\n";
- }
- #include <algorithm>
- #include <functional>
- #include <iostream>
- #include <string_view>
- #include <type_traits>
- #include <vector>
-
- void println(std::string_view rem, const auto& v)
- {
- std::cout << rem;
- if constexpr (std::is_scalar_v<std::decay_t<decltype(v)>>)
- std::cout << v;
- else
- for (int e : v)
- std::cout << e << ' ';
- std::cout << '\n';
- }
-
- int main()
- {
- const auto v0 = {4, 2, 5, 1, 3};
- std::vector<int> v1{10, 11, 12};
- std::vector<int> v2{10, 11, 12, 13, 14, 15, 16};
- std::vector<int>::iterator it;
-
- it = std::partial_sort_copy(v0.begin(), v0.end(), v1.begin(), v1.end());
- println("Writing to the smaller vector in ascending order gives: ", v1);
-
- if (it == v1.end())
- println("The return value is the end iterator", ' ');
-
- it = std::partial_sort_copy(v0.begin(), v0.end(), v2.begin(), v2.end(),
- std::greater<int>());
-
- println("Writing to the larger vector in descending order gives: ", v2);
- println("The return value is the iterator to ", *it);
- }
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。