fork download
  1. #include <iostream>
  2. #include <vector>
  3. #include <algorithm>
  4.  
  5. template <typename It>
  6. void SwapMinAndMax(It first, It last) {
  7. auto position_of_min = std::min_element(first, last);
  8. auto position_of_max = std::max_element(first, last);
  9. std::swap(*position_of_min, *position_of_max);
  10. }
  11.  
  12. template <typename E>
  13. std::ostream& operator<<(std::ostream& ostream,
  14. std::vector<E> const& elements) {
  15. for (const auto& element : elements) {
  16. ostream << element << " ";
  17. }
  18. return ostream;
  19. }
  20.  
  21. int main() {
  22. std::vector<int> array = {-1, 4, 7, 0, 5, 4, 8, 4, -22, 6};
  23. std::cout << "Elements before swap:\n" << array;
  24. SwapMinAndMax(std::begin(array), std::end(array));
  25. std::cout << "\nElements after swap:\n" << array;
  26. }
  27.  
Success #stdin #stdout 0s 3272KB
stdin
Standard input is empty
stdout
Elements before swap:
-1 4 7 0 5 4 8 4 -22 6 
Elements after swap:
-1 4 7 0 5 4 -22 4 8 6