I l@ve RuBoard Previous Section Next Section

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 ){ 


         cerr << "Unable to open file -- bailing out!\n"; 


         return -1; 


    } 





    vector<string> text; 


    string word; 





    while ( ifile >> word ) 


            text.push_back( word ); 





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


    display_vector( text, ofile ); 


} 

display_vector() is a function template parameterized on the element type of the vector passed to it to display:



template <typename elemType> 


void display_vector( const vector<elemType> &vec, 


                     ostream &os=cout, int len= 8 ) 


{ 


    vector<elemType>::const_iterator 


             iter = vec.begin(), 


             end_it = vec.end(); 





    int elem_cnt = 1; 


    while ( iter != end_it ) 


          os << *iter++ 


               << ( !( elem_cnt++ % len ) ? '\n' : ' '); 


    os << endl; 


} 

The input file is the same text used in Exercise 3.1. The output of this program looks like this:



a a a is to in is he 


is he not cow her says poor only 


Like arms with free break Alice kitty kitty 


looks black large white MooCat kitten MooCat patches 


cradling pretending struggling long-haired 

If we want to sort the words within each length alphabetically, we would first invoke sort() with the default less-than operator and then invoke stable_sort(), pass-ing it the LessThan function object. stable_sort() maintains the relative order of elements meeting the same sorting criteria.

    I l@ve RuBoard Previous Section Next Section