Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sort command line args in C++

Tags:

c++

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.

like image 638
Nicole Avatar asked Nov 19 '25 03:11

Nicole


1 Answers

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);
});
like image 156
Shreevardhan Avatar answered Nov 20 '25 17:11

Shreevardhan



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!