fork download
  1. #include <iostream>
  2.  
  3. #include <algorithm>
  4. #include <vector>
  5.  
  6. template <typename T, typename Comp>
  7. void insert_sorted(std::vector<T>& vec, T const& e, Comp const& comp) {
  8. auto const it = std::lower_bound(vec.begin(), vec.end(), e, comp);
  9.  
  10. if (it != vec.end() and not comp(e, *it)) { return; }
  11.  
  12. vec.insert(it, e);
  13. }
  14.  
  15. template <typename T>
  16. void insert_sorted(std::vector<T>& vec, T const& e) {
  17. insert_sorted(vec, e, std::less<T>{});
  18. }
  19.  
  20. int main() {
  21. int const array[] = { 4, 3, 6, 2, 3, 6, 8, 4 };
  22.  
  23. std::vector<int> vec;
  24. for (int a: array) {
  25. insert_sorted(vec, a);
  26. }
  27.  
  28. std::cout << vec.size() << ":";
  29. for (int a: vec) { std::cout << " " << a; }
  30. std::cout << "\n";
  31.  
  32. return 0;
  33. }
Success #stdin #stdout 0s 3476KB
stdin
Standard input is empty
stdout
5: 2 3 4 6 8