Exercise 3.2

Read in a text file — it can be the same one as in Exercise 3.1 — storing it in a vector. Sort the vector by the length of the string. Define a function object to pass to sort(); it should accept two strings and return true if the first string is shorter than the second. Print the sorted vector.

Let’s begin by defining the function object to pass to sort():

class LessThan { 
public: 
   bool operator()( const string & s1, 
                    const string & s2 ) 
      { return s1.size() < s2.size(); } 
}; 

The call to sort looks like this:

sort( text.begin(), text.end(), LessThan() ); 

The main program looks like this:

 int main() { ifstream ifile( "C:\\My Documents\\MooCat.txt" ); ofstream ofile( "C:\\My Documents\\MooCat.sort" ); if ( ! ifile || ! ofile ){ ...

Get Essential C++ now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.