【问题标题】:Sorting command line args排序命令行参数
【发布时间】:2021-02-06 10:54:14
【问题描述】:
#include <iostream>
#include <cstring>
#include <algorithm>
using namespace std;

bool comp(int a, int b){
    return a < b;
}

int main(int argc, char* argv[]){
    char array[argc-1];
    for(int i = 1; i < argc; i++){
        array[i-1] = *argv[i];
    }
    for(int j = 0; j < argc; j++){
        cout<<array[j]<<" ";
    }
    std::sort(array, array+argc-1, comp);
    for(int j = 0; j < argc; j++){
        cout<<array[j]<<" ";
    }
    cout<<endl;
    return 0;
}

此代码应该对命令行的参数进行排序。但是当我启动它时:

.\a.exe 11 21 34 9 87

我得到这个输出:

1 2 3 8 9

【问题讨论】:

  • 您只复制每个参数的第一个字符。
  • 是的,你得到这个输出是因为你的程序就是这么做的。它仅对每个参数的第一个字符进行排序。这就是你的程序所做的。如果你想让它做其他事情,你需要相应地改变你的程序。您的比较函数仅比较两个 int 值对您有意义吗?当实际比较只比较两个int 值时,您希望如何对字符串进行排序?您可以从拼图的这一部分开始,然后从那里开始。
  • 也许this 有帮助
  • arraychar 的数组,但您的比较函数比较两个 int 值。
  • 可变长度数组不符合 C++ 标准,你应该使用std::vector

标签: c++ sorting command-line-arguments


【解决方案1】:

Variable length arrays are not C++ standard compliant,你应该改用std::vector

在这种情况下,您甚至不需要这样做,您可以简单地对argv 进行排序,这只不过是一个字符串数组:

bool comp(const char* a, const char* b)
{
    return std::stoi(a) < std::stoi(b); // convert to number and compare
}

int main(int argc, char *argv[])
{
    try //if argument is not parseable, exception is thrown
    {
        std::sort(&argv[1], &argv[argc], comp);
    }
    catch (std::exception &e)
    {
        //error parsing argument handling
        std::cerr << "Argument not parseable " << e.what() << "\n";
        return EXIT_FAILURE;
    }

    for (int j = 1; j < argc; j++)
    {
        std::cout << argv[j] << " ";
    }
}

比较器函数也可以是一个 lambda,我相信您在 cmets 中提供的链接之一中有一个示例。

输入:

.\a.exe 11 21 34 9 87

输出:

9 11 21 34 87 

输入错误:

.\a.exe 11 21 34 9 87 gjh

输出:

Argument not parseable stoi

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2014-10-10
    • 2012-10-25
    • 1970-01-01
    • 2016-02-09
    • 1970-01-01
    • 2016-03-25
    • 2012-01-08
    • 1970-01-01
    相关资源
    最近更新 更多