当前位置:   article > 正文

C++ std::partial_sort_copy 用法

C++ std::partial_sort_copy 用法

一:功能

        部分排序,即选出前n个最大值或者最小值,并将其保存到另外一个容器中。

二:用法

  1. #include <vector>
  2. #include <algorithm>
  3. #include <iostream>
  4. #include <iterator>
  5. int main() {
  6. std::vector<int> top(3);
  7. auto input = std::istream_iterator<int>(std::cin);
  8. auto cnt = std::counted_iterator(input, 10);
  9. std::ranges::partial_sort_copy(cnt, std::default_sentinel,
  10. top.begin(), top.end(),
  11. std::greater<>{});
  12. for (auto v : top) {
  13. std::cout << v << " ";
  14. }
  15. std::cout << "\n";
  16. }
  1. #include <algorithm>
  2. #include <functional>
  3. #include <iostream>
  4. #include <string_view>
  5. #include <type_traits>
  6. #include <vector>
  7. void println(std::string_view rem, const auto& v)
  8. {
  9. std::cout << rem;
  10. if constexpr (std::is_scalar_v<std::decay_t<decltype(v)>>)
  11. std::cout << v;
  12. else
  13. for (int e : v)
  14. std::cout << e << ' ';
  15. std::cout << '\n';
  16. }
  17. int main()
  18. {
  19. const auto v0 = {4, 2, 5, 1, 3};
  20. std::vector<int> v1{10, 11, 12};
  21. std::vector<int> v2{10, 11, 12, 13, 14, 15, 16};
  22. std::vector<int>::iterator it;
  23. it = std::partial_sort_copy(v0.begin(), v0.end(), v1.begin(), v1.end());
  24. println("Writing to the smaller vector in ascending order gives: ", v1);
  25. if (it == v1.end())
  26. println("The return value is the end iterator", ' ');
  27. it = std::partial_sort_copy(v0.begin(), v0.end(), v2.begin(), v2.end(),
  28. std::greater<int>());
  29. println("Writing to the larger vector in descending order gives: ", v2);
  30. println("The return value is the iterator to ", *it);
  31. }

    

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/从前慢现在也慢/article/detail/853471
推荐阅读
相关标签
  

闽ICP备14008679号