如何在 c++ 中对命令行参数进行排序
How to sort command-line arguments in c++
我现在想做的只是对命令行参数进行排序,但我不断收到分段错误(核心转储(错误,我认为这意味着我有一个指针指向一个虚构的地方。
#include<iostream>
#include<cstdlib>
#include<algorithm>
#include<vector>
using namespace std;
int main (int argc, char* argv[]) {
vector<int> the_args;
vector<int>::iterator it;
it = the_args.begin(); //this seems logical to me.
int i = 1; //so I'll skip over argv[0]
while (i < argc)
{
the_args.insert (it, atoi(argv[i]));
i++;
it++;//this is probably the perpetrator.
}
sort (the_args.begin(), the_args.end());
for (it = the_args.begin(); it < the_args.end(); it++) //or else it's this
{
cout << *it << " ";
}
return 0;
}
我最终想编写游戏程序。我在 Java 方面有足够的经验,我想我可以开始尝试搞砸C++并弄清楚......但也许不是? 请善待你的回答,我真的很气馁,我什至不得不在这里问一个关于排序的问题。
在这里:
vector<string> the_args( argv + 1, argv + argc );
或:
vector<int> the_args;
for( int i = 1; i < argc; ++i )
{
the_args.push_back( atoi( argv[i] ) );
}
然后像你正在做的那样用std::sort
对它进行排序。
the_args.insert (it, atoi(argv[i]));
这使it
无效。废弃迭代器,只使用push_back
.
the_args.push_back(atoi(argv[i]));
或者,insert
将一个有效的迭代器返回到刚刚插入的对象,因此您也可以执行以下操作:
it = the_args.insert (it, atoi(argv[i]));
但是,如果您只是在向量的末尾插入,那就太复杂了。这里有一个选项可以替换你的整个循环,如果你是单行的粉丝:
std::transform(argv + 1, argv + argc, std::back_inserter(the_args), std::atoi);
尝试以下操作
#include<iostream>
#include<cstdlib>
#include<vector>
int main (int argc, char* argv[])
{
vector<int> the_args
if ( argc > 1 ) the_args.reserve( argc - 1 );
for ( int i = 1; i < argc; i++ ) the_args.push_back( std::atoi( argv[i] ) );
std::sort( the_args.begin(), the_args.end() );
for ( int x : the_args )
{
std::cout << x << " ";
}
std::cout << std::endl;
return 0;
}
相关文章:
- Constexpr 可变参数模板,用于对无符号整数进行重新排序
- 是否可以在调用链接器时强制 CMake 重新排序参数?
- C++17.处理使用 auto 相关的模板参数.代码排序困难
- 在C++排序中为比较函数指定参数
- 推力中的参数排序
- C++一个具有 2 个参数(___ _____,整数长度)的函数中的快速排序
- 函数参数:不确定排序还是未排序?
- 用于对可变数量的数组进行排序的可变参数模板
- 提升 MPL 排序模板参数包
- 按参数对向量进行排序
- 五个中三个最大参数的平均值,不使用排序算法或向量/数组
- 根据一个参数对数组进行排序
- 对于列表排序,有没有办法使用相同的参数让多个运算符重载?
- 通过提供指针数组作为参数对数组进行排序
- 使用按插入方式排序的参数创建哈希映射
- C++:如何使用类参数之一对派生自类的对象向量进行排序
- STL 按多个参数C++排序
- 谷歌C++风格指南.为什么要先输入后输出参数排序
- IDL文件和C++头文件中的defaultvalue和retval参数排序
- 基于额外参数排序向量