Re: STL: Could you make this snippet more efficient
pedagani@gmail.com wrote:
Could you make this snippet more efficient? As you see I have too many
variables introduced in the code.
//Read set of integers from a file on line by line basis in a STL set
//fp is pre-defined
for(;!fp.eof();)
{
string linestr;
getline(fp,linestr);
istringstream strstreamline(linestr);
istream_iterator<unsigned int> intstream(strstreamline);
set<unsigned int> pckset;
copy ( intstream , istream_iterator<unsigned int>() ,
inserter(modpckset,modpckset.begin ( ) ));
}
Thanks in advance.
First let's clean up the code you have.
set< unsigned int > modpckset; // has to be defined outside the loop
string line;
while ( getline( fp, line ) ) // proper way to read until end of file
{
istringstream ss( line );
copy( istream_iterator< unsigned int >( ss ),
istream_iterator< unsigned int >(),
inserter( modpckset, modpckset.begin() ) );
}
With the above code, getline will read in a line of the file at a time,
then parse it out to a bunch of unsigned ints. We don't need to do the
extra step:
set< unsigned int > modpckset;
copy( istream_iterator< unsigned int >( fp ),
istream_iterator< unsigned int >(),
inserter( modpckset, modpckset.begin() ) );
The above will do the same thing.
Now, if your goal was to read each line into a separate set, say you
want to end up with a vector of sets, then you would need to read each
line separately.
vector< set< unsigned int > > all_sets;
string line;
while ( getline( fp, line ) )
{
istringstream ss( line );
all_sets.push_back( set< unsigned int >() );
copy( istream_iterator< unsigned int >( ss ),
istream_iterator< unsigned int >(),
inserter( all_sets.back(), all_sets.back().begin() ) );
}