在C ++中对命令行参数进行排序

时间:2017-01-27 04:42:39

标签: c++

我想对一系列命令行参数进行排序。所有参数都是整数。 这是我的代码,但它不起作用。

#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;
    }
}

编译完成后,当我拨打./a.out 4 3 2 1时,它仍然会将4 3 2 1打印到屏幕而不是1 2 3 4。 怎么了?

提前致谢。

2 个答案:

答案 0 :(得分:5)

使用自定义比较器

std::sort尝试<algorithm>
std::sort(argv, argv + argc, [](char * const & a, char * const & b) {
    return atoi(a) < atoi(b);
});

答案 1 :(得分:1)

在现代c ++中,您可以将auto类型用于lambda。对于字符串到int转换,我希望stoi函数优于atoi(您可以查找差异here)。还值得注意的是,第一个参数(argv[0])是一个程序名称,例如./a.out,因此您需要从排序中跳过它。最终结果可能如下所示:

#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, " "));
}

如果所有命令行参数都是具有固定数字的无符号数,则您也可以将它们排序为字符串,即不通过std::stoi显式转换为数字。在这种情况下,可以使用std::vector<std::string>

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

不需要为std::sort使用lambda或其他自定义比较器。