在C++中对命令行参数进行排序
Sort command line args in 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
。怎么了?
提前谢谢。
尝试使用自定义比较器从<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
。
相关文章:
- Constexpr 可变参数模板,用于对无符号整数进行重新排序
- 是否可以在调用链接器时强制 CMake 重新排序参数?
- C++17.处理使用 auto 相关的模板参数.代码排序困难
- 在C++排序中为比较函数指定参数
- 推力中的参数排序
- C++一个具有 2 个参数(___ _____,整数长度)的函数中的快速排序
- 函数参数:不确定排序还是未排序?
- 用于对可变数量的数组进行排序的可变参数模板
- 提升 MPL 排序模板参数包
- 按参数对向量进行排序
- 五个中三个最大参数的平均值,不使用排序算法或向量/数组
- 根据一个参数对数组进行排序
- 对于列表排序,有没有办法使用相同的参数让多个运算符重载?
- 通过提供指针数组作为参数对数组进行排序
- 使用按插入方式排序的参数创建哈希映射
- C++:如何使用类参数之一对派生自类的对象向量进行排序
- 快速排序参数
- 合并排序 c++ 1 参数 - 向量
- 快速排序函数C++ 1 个参数 - 向量
- STL 按多个参数C++排序