3

I wanna sort an array of command line arguments. All arguments are integer. Here is my code, but it does not work.

#include <iostream>
using namespace std;

int main (int argc, char *argv[]) {
    for (int i=0; i<argc-1; ++i) {
        int pos = i;
        for (int j=i+1; j<argc; ++j) {
            if (argv[j] - '0' < argv[pos] - '0') {
                pos = j;
            }
        }
        char *tempt = argv[i];
        argv[i] = argv[pos];
        argv[pos] = tempt;
    }
    for (int i=0; i<argc; ++i) {
        cout << argv[i] <<endl;
    }
}

After compiling, when I called ./a.out 4 3 2 1, it still printed 4 3 2 1 to the screen instead of 1 2 3 4. What's wrong?

Thanks in advance.

Shreevardhan
  • 12,233
  • 3
  • 36
  • 50
Nicole
  • 33
  • 3

2 Answers2

5

Try std::sort from <algorithm> with a custom comparator

std::sort(argv, argv + argc, [](char * const & a, char * const & b) {
    return atoi(a) < atoi(b);
});
Shreevardhan
  • 12,233
  • 3
  • 36
  • 50
2

In modern c++ you can use auto types for lambdas. For string to int convertion I would prefer stoi function over atoi (you can look for differences here). Also worth noting that first argument (argv[0]) is a program name, e.g. ./a.out, so you need to skip it from sorting. Final result could be looks like this:

#include <algorithm>
#include <iostream>
#include <iterator>
#include <string>

int main (int argc, char *argv[]) {

    std::sort(argv + 1, argv + argc, [](auto l, auto r){ return std::stoi(l) < std::stoi(r); } );
    std::copy(argv + 1, argv + argc, std::ostream_iterator<const char*>(std::cout, " "));
}

If all of command line arguments a unsigned number with fixed digits count you could also sort them like string, i.e. without explicit converting to numbers via std::stoi. In this case std::vector<std::string> could be used:

std::vector<std::string> v(argv + 1, argv + argc);
std::sort(v.begin(), v.end());

There is no need to use lambda or another custom comparator for std::sort.

Community
  • 1
  • 1
αλεχολυτ
  • 4,792
  • 1
  • 35
  • 71