fork download
  1. #include <iostream>
  2. #include <cassert>
  3. #include <algorithm>
  4. #include <string>
  5. #include <vector>
  6. using namespace std;
  7.  
  8. bool howToCompare(string i, string j) {
  9. // check that strings are ok
  10. assert (i.find_first_not_of("01234567890")==string::npos);
  11. assert (j.find_first_not_of("01234567890")==string::npos);
  12. // handle size difference with leading 0
  13. if(i.length() < j.length()) {
  14. i = string( j.length()-i.length(),'0')+i;
  15. }
  16. else if(i.length() > j.length()) {
  17. j = string(i.length()-j.length(),'0')+j;
  18. }
  19. // compare strings of same size
  20. for(int k = 0; k < i.length(); k++) {
  21. if(i[k] != j[k] ) {
  22. return i[k] < j[k];
  23. }
  24. }
  25. return false;
  26. }
  27.  
  28. int main() {
  29. int n;
  30. cin >> n;
  31.  
  32. vector<string> array(n);
  33. for(int i = 0; i < n; i++) {
  34. cin >> array[i];
  35. }
  36.  
  37. sort(array.begin(), array.end(), howToCompare);
  38.  
  39. for(int i = 0; i < n; i++) {
  40. cout << array[i] << endl;
  41. }
  42. return 0;
  43. }
Success #stdin #stdout 0s 15248KB
stdin
8
30
40
7
10
118
05
12
45
stdout
05
7
10
12
30
40
45
118