【问题标题】:How to sort command-line arguments in c++如何在 C++ 中对命令行参数进行排序
【发布时间】:2014-10-10 05:15:09
【问题描述】:

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

#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++ 中搞砸并弄清楚......但也许不是?请你的回答很好,我真的很沮丧,我什至不得不在这里问一个关于排序的问题。

【问题讨论】:

标签: c++ sorting vector iterator arguments


【解决方案1】:

这里:

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 对其进行排序。

【讨论】:

  • @quantdev: to_stringatoi 走向相反的方向。如果想要检查错误,strtol 很好。
【解决方案2】:
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);

【讨论】:

    【解决方案3】:

    试试下面的

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-11-27
      • 2012-10-25
      • 1970-01-01
      • 2021-02-06
      • 2023-03-20
      • 1970-01-01
      • 1970-01-01
      • 2013-10-30
      相关资源
      最近更新 更多