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

Sort command line args in C++

本文关键字:排序 参数 命令行 C++      更新时间:2023-10-16

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

#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。怎么了?

提前谢谢。

尝试使用自定义比较器从<algorithm> std::sort

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

在现代 c++ 中,你可以对 lambda 使用auto类型。对于字符串到整数的转换,我更喜欢stoi函数而不是atoi(您可以在此处查找差异)。另外值得注意的是,第一个参数(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());

无需使用 lambda 或其他自定义比较器进行std::sort