0

All I want to do for right now is sort command-line arguments, but I keep getting a segmentation fault (core dumped) error, which I think means I have a pointer pointing at an imaginary place.

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

I eventually want to program games. I've got enough experience in Java that I figured I could start trying to screw around in C++ and figure it out... but maybe not? Please be nice in your answers, I'm really discouraged that I even have to ask a question on here about sorting something.

ABvsPred
  • 67
  • 7
  • 1
    just use `push_back`, `insert` is invalidating `it`. – quantdev Aug 16 '14 at 20:52
  • just use `Boost.Program_options` http://www.boost.org/doc/libs/1_56_0/doc/html/program_options.html and do yourself a favor . – user2485710 Aug 16 '14 at 20:54
  • Knowing some Java and "trying to screw around" is going to be a slow and error-filled way to learn C++. Can I suggest a good book instead? [The Definitive C++ Book Guide and List](http://stackoverflow.com/q/388242/445976) – Blastfurnace Aug 16 '14 at 20:59

3 Answers3

4

Here:

vector<string> the_args( argv + 1, argv + argc );

Or:

vector<int> the_args;
for( int i = 1; i < argc; ++i ) 
{
    the_args.push_back( atoi( argv[i] ) );
}

Then just sort it with std::sort as you’re doing.

Cheers and hth. - Alf
  • 142,714
  • 15
  • 209
  • 331
3
the_args.insert (it, atoi(argv[i]));

This invalidates it. Scrap the iterator, and just use push_back.

the_args.push_back(atoi(argv[i]));

Alternatively, insert returns a valid iterator to the object that was just inserted, so you could also do this:

it = the_args.insert (it, atoi(argv[i]));

But that's unnecessarily complicated if you are just inserting at the end of the vector. Here's an option which replaces your entire loop, if you're a fan of one-liners:

std::transform(argv + 1, argv + argc, std::back_inserter(the_args), std::atoi);
Benjamin Lindley
  • 101,917
  • 9
  • 204
  • 274
1

Try the following

#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;
}
Vlad from Moscow
  • 301,070
  • 26
  • 186
  • 335