I l@ve RuBoard Previous Section Next Section

Solution

graphics/bulb_icon.gif

With no other changes, simply using the standard find() algorithm could have avoided two temporaries, as well as the emps.end() recomputation inefficiency from the original code. For the best effect to reduce temporaries, provide an operator==() taking an Employee& and a name string&.



string FindAddr( list<Employee> emps, string name ) 


{


  list<Employee>::iterator i(


    find( emps.begin(), emps.end(), name )


    );


  if( i != emps.end() )


  {


    return i->addr;


  }


  return "";


}


Yes, you can get even fancier with functors and find_if, but see how much this simple reuse of find saves in programming effort and run-time efficiency.

Guideline

graphics/guideline_icon.gif

Reuse code梕specially standard library code梚nstead of handcrafting your own. It's faster, easier, and safer.


Reusing existing code is usually preferable to handcrafting your own. The standard library is full of code that's intended to be used and reused, and to that end a lot of thought and care has gone into the design of the library, including its standard algorithms, such as find() and sort(). Implementers have spent hours sweating over efficiency details, usability details, all sorts of other considerations so that you don't have to. So reuse code, especially code in the standard library, and escape the trap of "I'll-write-my-own."

Combining this with the other fixes, we get a much improved function.



string FindAddr( const list<Employee>& emps, 


                 const string&         name )


{


  list<Employee>::const_iterator i(


    find( emps.begin(), emps.end(), name )


    );


  if( i != emps.end() )


  {


    return i->addr;


  }


  return "";


}


    I l@ve RuBoard Previous Section Next Section