如何在 c++ 中对命令行参数进行排序

How to sort command-line arguments in c++

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

我现在想做的只是对命令行参数进行排序,但我不断收到分段错误(核心转储(错误,我认为这意味着我有一个指针指向一个虚构的地方。

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