fork download
  1. #include <iostream>
  2. #include <vector>
  3. #include <algorithm>
  4.  
  5. using namespace std;
  6.  
  7. /// Prints content of the vector
  8. /// \param array - vector to prints content of
  9. void printVector(vector<int> array) {
  10. for (int el : array) {
  11. cout << el << " ";
  12. }
  13.  
  14. cout << endl;
  15. }
  16.  
  17. /// Compute absolute value of given integer
  18. /// \param a - integer to compute an absolute value of
  19. /// \return Absolute value of a
  20. int abs(int a) {
  21. if (a < 0) {
  22. return -a;
  23. } else {
  24. return a;
  25. }
  26. }
  27.  
  28. /// Compare two elements using their absolute values
  29. /// \param a - first value
  30. /// \param b - second value
  31. /// \result true if absolute value of a is lower than absolute value of b, false otherwise
  32. bool compare(int a, int b) {
  33. return abs(a) < abs(b);
  34. }
  35.  
  36. int main() {
  37. vector<int> array;
  38. array.push_back(5);
  39. array.push_back(-2);
  40. array.push_back(-6);
  41. array.push_back(12);
  42. array.push_back(0);
  43.  
  44. cout << "Sorting array in ascending order" << endl;
  45. sort(array.begin(), array.end());
  46. printVector(array);
  47.  
  48. cout << "Sorting array in descending order" << endl;
  49. sort(array.rbegin(), array.rend());
  50. printVector(array);
  51.  
  52. cout << "Sorting array using custom comparing function" << endl;
  53. sort(array.begin(), array.end(), compare);
  54. printVector(array);
  55.  
  56. return 0;
  57. }
Success #stdin #stdout 0s 5556KB
stdin
Standard input is empty
stdout
Sorting array in ascending order
-6 -2 0 5 12 
Sorting array in descending order
12 5 0 -2 -6 
Sorting array using custom comparing function
0 -2 5 -6 12