-1

I saw someone use this line to remove white spaces from string stored in a vector, but I fail to understand the reason for using erase and remove this way? The second question: how can I, instead of only removing white spaces, remove anything that is not a 'num' or a '-' ?

this is not the full code, it is only a snippet, will not compile. the vector simply contains raw strings of a text file, the strings were comma delimited, currently the strings could contain any possible char except the comma.

vector <string> vecS;
ifstream vecStream;
while(vecStream.good()) {
 vecS.resize(i+1);
 getline(vecStream, vecS.at(i), ',');
 vector <string> vecS;          
 vecS.at(i).erase(remove( vecS.at(i).begin(), vecS.at(i).end(), ' '), vecS.at(i).end());
 i++
}

EDIT; added more code, hope this is clearer now

Molegrammer
  • 193
  • 1
  • 9

1 Answers1

1

but I fail to understand the reason for using erase and remove this way?

std::remove basically rearranges the sequence so that the elements which are not to be removed are all shifted to the beginning of the sequence - a past-the-end iterator for that part, and effectively the new end of the sequence, is then returned.

There is absolutely no need for a file stream in that snippet though:

vector <string> vecS;
// Do something with vecS

for( auto& s : vecS )   
    s.erase( remove_if( std::begin(s), std::end(s), 
                        [](char c){ return std::isspace(c); }), // Use isspace instead, that recognizes all white spaces
             std::end(s) );
Columbo
  • 60,038
  • 8
  • 155
  • 203