STL sort in C++

Level 4204 keystrokes

Sorts a vector in ascending order with sort, then in descending order by passing greater<int>() as the comparator.

C++ code

1vector<int> nums = {5, 2, 8, 1, 9};
// Sort the whole range in ascending order (uses operator< by default)
2sort(nums.begin(), nums.end());
// Print 1 2 5 8 9, each followed by a space
3for (int n : nums) cout << n << " ";
// End the first line
4cout << endl;
5
// greater<int>() compares with >, so the order becomes descending
6sort(nums.begin(), nums.end(), greater<int>());
// Print 9 8 5 2 1
7for (int n : nums) cout << n << " ";

Output

1 2 5 8 9 
9 8 5 2 1 
Practice typing this code

Practice typing this code. Results are not recorded in the rankings.

Symbols in this code

The symbols you type in this C++ code and how often they appear.

  • <× 12
  • (× 9
  • )× 9
  • ,× 7
  • ;× 6
  • .× 4
  • "× 4
  • :× 2
  • >× 2
  • {× 1

More C++ examples at level 4

← C++ typing practice