i have a problem... i wanna make a function that takes a string as input splits it, storing the resulting strings in a vector<string> and then sort it

#include <iostream>
#include <vector>
#include <iterator>
#include <sstream>

using namespace std;

vector<string> split( const string &sInput  )
{
	istringstream is( sInput );
	vector<string> vect;
	copy( istream_iterator<string>(is) , istream_iterator<string>() , vect.begin() );
	sort( vect.begin() , vect.end() );
	return vect;

}

int main(int argc, char* argv[])
{
	if(argc != 2) return 1;
	string sForSplit = argv[1];
	vector<string> vect;
	vect = split( sForSplit );
	ostream_iterator<string> os( cout ,"\n");
	copy ( vect.begin(), vect.end() , os );

}

it compiles, but when i run it i get Segmentation Fault

can anyone explain me why? i don't want to implement the function without the istream_iterator, done that before, i just want to know where does the runtime error occur and why.
thx

Recommended Answers

All 2 Replies

>vector<string> vect;
>copy( istream_iterator<string>(is) , istream_iterator<string>() , vect.begin() );
The vector is empty, and copy won't call push_back for you. You need to add a back_inserter to the destination or copy will write to memory that you don't own:

copy( istream_iterator<string>(is) ,
  istream_iterator<string>() , back_inserter( vect ) );

You also need to include <algorithm> if you plan to use the sort function.

>vector<string> vect;
>copy( istream_iterator<string>(is) , istream_iterator<string>() , vect.begin() );
The vector is empty, and copy won't call push_back for you. You need to add a back_inserter to the destination or copy will write to memory that you don't own:

copy( istream_iterator<string>(is) ,
  istream_iterator<string>() , back_inserter( vect ) );

You also need to include <algorithm> if you plan to use the sort function.

true, :P thx

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.