Effective stl notes
Upcoming SlideShare
Loading in...5
×
 

Like this? Share it with your network

Share

Effective stl notes

on

  • 1,025 views

Effective STL Notes, a presentation I prepared for training at Synerzip.

Effective STL Notes, a presentation I prepared for training at Synerzip.

Statistics

Views

Total Views
1,025
Views on SlideShare
993
Embed Views
32

Actions

Likes
3
Downloads
26
Comments
2

3 Embeds 32

http://cppelevan.wordpress.com 25
http://www.linkedin.com 5
http://www.slashdocs.com 2

Accessibility

Categories

Upload Details

Uploaded via as Adobe PDF

Usage Rights

© All Rights Reserved

Report content

Flagged as inappropriate Flag as inappropriate
Flag as inappropriate

Select your reason for flagging this presentation as inappropriate.

Cancel
  • Full Name Full Name Comment goes here.
    Are you sure you want to
    Your message goes here
    Processing…
  • Hey Srinivas, Thanks for comments. I did not record audio/video, I will definitely do next time I present this :) Thanks again for comments and suggestion
    Are you sure you want to
    Your message goes here
    Processing…
  • Uttam, very good slides. Like to hear related lecture from you. Why don't you upload a video/audio of your lecture on youtube. And share with us -srinivas godaba
    Are you sure you want to
    Your message goes here
    Processing…
Post Comment
Edit your comment

Effective stl notes Presentation Transcript

  • 1. Effective STL Notes UTTAM GANDHI, SOFTWARE DEVELOPER
  • 2. Pre-requisites—  C++—  Data Structure—  Templates—  Smart Pointers—  Constant Time, Logarithmic, LinearUttam Gandhi, Software Developerhttp://www.linkedin.com/pub/uttam-gandhi/21/7aa/24 Content last revised on 1/4/13
  • 3. Acknowledgments—  This presentation is based on Scott Meyers well known book ‘Effective STL’Uttam Gandhi, Software Developerhttp://www.linkedin.com/pub/uttam-gandhi/21/7aa/24 Content last revised on 1/4/13
  • 4. Why STL—  Contains most useful algorithms and data structures—  Established programming techniques, idioms and styles—  Usually very-well tested—  Usually highly optimized (might use optimizations that are not available to ordinary programmer)—  Ref-- http://www.cs.helsinki.fi/u/tpkarkka/alglib/ k06/lectures/stl_intro.htmlUttam Gandhi, Software Developerhttp://www.linkedin.com/pub/uttam-gandhi/21/7aa/24 Content last revised on 1/4/13
  • 5. STL Intro duction—  STL consists of ¡  Containers ¡  Algorithms ¡  IteratorsUttam Gandhi, Software Developerhttp://www.linkedin.com/pub/uttam-gandhi/21/7aa/24 Content last revised on 1/4/13
  • 6. Containers—  Types of container ¡  Sequence containers ÷  vector ÷  list ÷  string ÷  deque ¡  Associative Containers ÷  set ÷  multiset ÷  map ÷  multimap ÷  unordered_map (C++ 11)Uttam Gandhi, Software Developerhttp://www.linkedin.com/pub/uttam-gandhi/21/7aa/24 Content last revised on 1/4/13
  • 7. Containers—  Container type based on allocation ¡  Contiguous-memory containers ÷  Insertion and deletion causes movement of elements ÷  vector, string, deque ¡  Node-based containers ÷  Insertion and deletion changes pointers, not nodes ÷  list and all associative containersUttam Gandhi, Software Developerhttp://www.linkedin.com/pub/uttam-gandhi/21/7aa/24 Content last revised on 1/4/13
  • 8. How to choose your container—  Insert element at an arbitrary position—  Ordering of elements in the container—  Category of iterators—  Is it important to avoid movement of existing container elements when insertions or erasures take place?—  Layout compatible with C—  container uses reference countingUttam Gandhi, Software Developerhttp://www.linkedin.com/pub/uttam-gandhi/21/7aa/24 Content last revised on 1/4/13
  • 9. Containers do Copy—  Containers make copies of object ¡  Storing ¡  Retrieving ¡  Insert/Delete causes movement of objects by copying ¡  Sorting algorithms—  Copying is done using copy constructor and copy assignment operator—  Copying should be efficient—  Copying can lead to slicingUttam Gandhi, Software Developerhttp://www.linkedin.com/pub/uttam-gandhi/21/7aa/24 Content last revised on 1/4/13
  • 10. Making Copy Efficient—  Use pointers ¡  Efficient, as bitwise copy will be made ¡  No slicing ¡  But possibility of memory leak ¡  Use smart pointers (self managed/shared/intrusive) ¡  Ref http://onlamp.com/pub/a/onlamp/2006/05/04/smart- pointers.html?page=5—  Still STL containers are better than C data structure ¡  Widget w[maxNumWidgets]; ¡  vector<widget> vw; ¡  vw.reserve(maxNumWidgets)Uttam Gandhi, Software Developerhttp://www.linkedin.com/pub/uttam-gandhi/21/7aa/24 Content last revised on 1/4/13
  • 11. Use empty than size==0—  Use empty, rather than checking size == 0 ¡  For some list implementation, size takes linear time ¡  Why ¢  Splice operation moves elements from one list to other without copying elements ¢  If, size operation has to be constant then every list operation should update size ¢  This means, splice operation will take linear time ¢  One of the two can be constant but not both ¡  empty() will always be constantUttam Gandhi, Software Developerhttp://www.linkedin.com/pub/uttam-gandhi/21/7aa/24 Content last revised on 1/4/13
  • 12. Prefer range member functions 1/3—  vector<Widget> v1, v2; for ( vector<Widget>::const_iterator ci = v2.begin(); ci != v2.end(); ++ci) v1.push_back(*ci); ¡  lengthy code ¡  for loop—  copy(v2.begin(), v2.end(), back_inserter(v1 )); ¡  For loop is inside copy implementation—  v1 .insert(v1 .end(), v2.begin(),v2.end()); ¡  Short code ¡  Clear to understandUttam Gandhi, Software Developerhttp://www.linkedin.com/pub/uttam-gandhi/21/7aa/24 Content last revised on 1/4/13
  • 13. Prefer range member functions 2/3—  Efficiency Hits ¡  Inserting one element at a time, makes numValues calls of insert ÷  Range function will make single insert call, so numValues-1 less calls ÷  Inlining could have saved, but its not guaranteed ÷  Range insert will always be efficient ¡  Inserting element will cause movement of elements by copying them ÷  Every element will be shifted at least numValues times ÷  Shifting of primitive will require bitwise copy ÷  For user defined type, calls to assignment operator or copy constructorUttam Gandhi, Software Developerhttp://www.linkedin.com/pub/uttam-gandhi/21/7aa/24 Content last revised on 1/4/13
  • 14. Prefer range member functions 3/3—  Efficiency Hits ¡  Inserting element in vector can cause reallocations ÷  In case of range insert, reallocation would be 1 at max ÷  inserting numValues new elements could result in new memory being allocated up to log2numValues ÷  inserting 1000 elements one at a time can result in 10 new allocationsUttam Gandhi, Software Developerhttp://www.linkedin.com/pub/uttam-gandhi/21/7aa/24 Content last revised on 1/4/13
  • 15. Use delete for new element in container 1/3void doSomething(){vector<Widget*> vwp;for (int i = 0; i < SOME_MAGIC_NUMBER; ++i)vwp.push_back(new Widget);… // use vwp}This is a leakUttam Gandhi, Software Developerhttp://www.linkedin.com/pub/uttam-gandhi/21/7aa/24 Content last revised on 1/4/13
  • 16. Use delete for new element in container 2/3void doSomething(){vector<Widget*> vwp;… // as beforefor (vector<Widget*>::iterator i = vwp.begin();i != vwp.end(),++i) {delete *i;} still there can be leak because of exceptionUttam Gandhi, Software Developerhttp://www.linkedin.com/pub/uttam-gandhi/21/7aa/24 Content last revised on 1/4/13
  • 17. Use delete for new element in container 3/3void doSomething(){typedef boost::shared_ ptr<Widget> SPW;vector<SPW> vwp;for (int i = 0; i < SOME_MAGIC_NUMBER; ++i)vwp.push_back(SPW new Widget)… // use vwp} // no Widgets are leaked here, not // even if an exception is thrown//in the code aboveUttam Gandhi, Software Developerhttp://www.linkedin.com/pub/uttam-gandhi/21/7aa/24 Content last revised on 1/4/13
  • 18. Choosing Erasing Options—  Erase remove for sequence containers ¡  c.erase( remove(c.begin(), c.end(), 1963), c.end()); ¡  remove function being receives only iterator (no container) ¡  remove takes linear time—  List ¡  c. remove(1963);—  Associative container ¡  c.erase(1963); ¡  Takes logarithmic timeUttam Gandhi, Software Developerhttp://www.linkedin.com/pub/uttam-gandhi/21/7aa/24 Content last revised on 1/4/13
  • 19. Choosing Erasing Options—  Erase remove for sequence containers ¡  c.erase( remove_if(c.begin(), c.end(),badValue), c.end()); ¡  badValue is the predicate—  List ¡  c. remove_if(1963);—  Associative container ¡  simple but does not work due to iterator invalidation ¡  The iterator pointing to erase becomes invalid, after execution of eraseAssocContainer<int> c;......for (AssocContainer<int>::iterator i = c.begin();i!= c.end(); ++i) {if (badValue(*i)) c.erase(i);}Uttam Gandhi, Software Developerhttp://www.linkedin.com/pub/uttam-gandhi/21/7aa/24 Content last revised on 1/4/13
  • 20. Choosing Erasing OptionsAssocContainer<int> c;for (AssocContainer<int>::iterator i = c.begin(); i !=c.end(); ){if (badValue(*i)) c.erase(i++);else ++i;} ¡  If there is a match erase is done using i ¡  i is incremented as a side-effect (before erase is executed) ¡  Effectively i is incremented before invalidatingUttam Gandhi, Software Developerhttp://www.linkedin.com/pub/uttam-gandhi/21/7aa/24 Content last revised on 1/4/13
  • 21. Prefer vector and string—  Dynamic Allocation ¡  Ensure delete is called for every new, else leak ¡  Ensure delete[] is called for array ¡  Ensure delete called only once—  Vector and string advantages ¡  Manage own memory ¡  Offer useful member functions like size, iterators, erase ¡  Can be used with legacy C code using array and char*—  Drawback ¡  string uses ref counting ¡  Causes overhead of concurrency control in multithreaded environment ¡  http://www.gotw.ca/publications/optimizations.htmUttam Gandhi, Software Developerhttp://www.linkedin.com/pub/uttam-gandhi/21/7aa/24 Content last revised on 1/4/13
  • 22. Prefer vector and string—  Solution ¡  Disable ref counting by changing pre-processor variable, may not be portable ¡  Find alternative string implementation ¡  Use vector<char> ÷  stringfunctions will not be available ÷  But STL algorithms will serve the purpose J—  Avoiding reallocation in vector ¡  Use reserveUttam Gandhi, Software Developerhttp://www.linkedin.com/pub/uttam-gandhi/21/7aa/24 Content last revised on 1/4/13
  • 23. Pass vector and string to legacy API—  Vector ¡  void doSomething(const int* pInts, size_t numlnts); ¡  doSomething(&v[0], v.size()); ¡  Frankly, if youre hanging out with people who tell you to use v.begin() instead of &v[0], you need to rethink your social circle. ¡  v can be modified but no new element should be added ¡  size_t fillArray(double *pArray, size_t arraySize); ¡  vector<double> vd(maxNumDoubles); ¡  vd.resize(fillArray(&vd[0], vd.size())); ¡  list<double> l(vd.begin(), vd.end());Uttam Gandhi, Software Developerhttp://www.linkedin.com/pub/uttam-gandhi/21/7aa/24 Content last revised on 1/4/13
  • 24. Pass vector and string to legacy API—  String ¡  void doSomething(const char *pString); ¡  doSomething(s.c_str());Uttam Gandhi, Software Developerhttp://www.linkedin.com/pub/uttam-gandhi/21/7aa/24 Content last revised on 1/4/13
  • 25. Use swap to trim excess capacity—  class Contestant {...};—  vector<Contestant> contestants;—  vector<Contestant>(contestants).swap(contestants); ¡  Temporary vector gets created using copy constructor ¡  It is created by the existing size (shrink) ¡  Swap happens, now temporary holds excess capacity ¡  At the end of statement temporary is destroyedUttam Gandhi, Software Developerhttp://www.linkedin.com/pub/uttam-gandhi/21/7aa/24 Content last revised on 1/4/13
  • 26. Equality and Equivalence 1/3—  Equality is based on ==, “x==y” ¡  Widget w1, w2 ¡  w1 == w2 returns true—  Equivalence is based on operator < ¡  !(w1 < w2) && !(w2 < w1) ¡  Equivalence is based on the relative ordering of object values in a sorted range ¡  Used in storing, retrieving in associative container ¡  two values are equivalent (with respect to some ordering criterion) if neither precedes the other (according to that criterion)Uttam Gandhi, Software Developerhttp://www.linkedin.com/pub/uttam-gandhi/21/7aa/24 Content last revised on 1/4/13
  • 27. Equality and Equivalence 2/3—  !c.key_comp()(x, y) && !c.key_comp()(y, x)struct CiStrCom:public binary_function<string, string,bool> {bool operator()(const string& lhs, const string& rhs)const { return ciStringCompare(lhs, rhs); }}set<string, CiStrCom> ciStringSet;Uttam Gandhi, Software Developerhttp://www.linkedin.com/pub/uttam-gandhi/21/7aa/24 Content last revised on 1/4/13
  • 28. Equality and Equivalence 3/3—  ciss.insert("Persephone"); // a new element is added to the set—  ciss.insert("persephone"); // no new element is added to the set—  if (ciss.find("persephone") != ciss.end())... // this test will succeed ¡  Uses equivalence, so works—  if (find( ciss.begin(), ciss.end(), "persephone") != ciss.end())... // this test will fail ¡  Uses equality, fails in this caseUttam Gandhi, Software Developerhttp://www.linkedin.com/pub/uttam-gandhi/21/7aa/24 Content last revised on 1/4/13
  • 29. Overriding default comp function—  When you declare set of string pointer ¡  set<string*> ssp; ¡  ssp.insert(newstring("Anteater")); ¡  ssp.insert(newstring("Wombat")); ¡  ssp.insert(new string(“Lemur")); ¡  ssp.insert(newstring("Penguin"));—  Default sort function is provided by STL ¡  In this case default function will do pointer value comparison ¡  For string comparison, you must provide own functor ¡  set<string*, less<string*> > ssp;Uttam Gandhi, Software Developerhttp://www.linkedin.com/pub/uttam-gandhi/21/7aa/24 Content last revised on 1/4/13
  • 30. Functor for string dereferencestruct StringPtrLess: public binary_function<conststring*, const string*, bool> {bool operator()(const string *ps1, const string *ps2)const {return *ps1 < *ps2;}};typedef set<string*, StringPtrLess> StringPtrSet ;StringPtrSet ssp;Uttam Gandhi, Software Developerhttp://www.linkedin.com/pub/uttam-gandhi/21/7aa/24 Content last revised on 1/4/13
  • 31. Templatized functor for de-referencestruct DereferenceLess {template <typename PtrType>bool operator()(PtrType pT1, PtrType pT2) constvalue, because we expect them{return *pT1 < *pT2;}};Uttam Gandhi, Software Developerhttp://www.linkedin.com/pub/uttam-gandhi/21/7aa/24 Content last revised on 1/4/13
  • 32. Comp should return false for equal value 1/2—  set<int, less_equal<int> > s; // s is sorted by "<="—  s.insert(10); //insert the value 10—  Now try inserting 10 again:—  s.insert(10);—  !(10A<= 10B)&&!(10B<= 10A) //test 10Aand 10B for equivalence—  set concludes that 10A and 10B are not equivalentUttam Gandhi, Software Developerhttp://www.linkedin.com/pub/uttam-gandhi/21/7aa/24 Content last revised on 1/4/13
  • 33. Comp should return false for equal value 2/2—  multiset<int, less_equal<int> > s; // s is still sorted by "<="—  s.insert(10); //insert 10A—  s.insert(10); // insert 10B ¡  equal_range on it, well get back a pair of iterators that define a range containing both copies ¡  equal_range identifies a range of equivalent valuesUttam Gandhi, Software Developerhttp://www.linkedin.com/pub/uttam-gandhi/21/7aa/24 Content last revised on 1/4/13
  • 34. In-place modification of set/multiset value1/2—  Map/multimap key modification will not compile—  Set object is not const because you still want to modify other properties of object—  If property/value used for sorting is modified, the container is corruptUttam Gandhi, Software Developerhttp://www.linkedin.com/pub/uttam-gandhi/21/7aa/24 Content last revised on 1/4/13
  • 35. In-place modification of set/multiset value2/2Uttam Gandhi, Software Developerhttp://www.linkedin.com/pub/uttam-gandhi/21/7aa/24 Content last revised on 1/4/13
  • 36. Sorted vector v/s associative container 1/3—  Standard associative container ¡  Typically implemented as balanced binary trees ¡  optimized for mix of lookup, insertion and deletion ¡  No way to predict the next operation—  Typical application usage of container ¡  Setup ÷  All operation are insert/delete, hardly any lookup ¡  Lookup ÷  Almost all operations are lookup ¡  Reorganize ÷  Modify, insert/delete, sortUttam Gandhi, Software Developerhttp://www.linkedin.com/pub/uttam-gandhi/21/7aa/24 Content last revised on 1/4/13
  • 37. Sorted vector v/s associative container 2/3—  For such usage, sorted vector can provide better performance ¡  Size ÷  Less size per element in vector, so storing takes less space ÷  Will lead to less page fault ÷  As vector offer better locality of reference ÷  Insertion/deletion can be costly, so not useful if application requires too many of theseUttam Gandhi, Software Developerhttp://www.linkedin.com/pub/uttam-gandhi/21/7aa/24 Content last revised on 1/4/13
  • 38. Sorted vector v/s associative container 3/3Uttam Gandhi, Software Developerhttp://www.linkedin.com/pub/uttam-gandhi/21/7aa/24 Content last revised on 1/4/13
  • 39. map::operator[] and map-insert 1/2—  map::operator[] ¡  Provides add/update functionality ¡  Returns reference to value ¡  If object does not exists, ÷  creates default constructed object ÷  insert in map ÷  Destructor of temporary object ÷  Assignment ¡  If insert is called directly, 3 function calls are savedUttam Gandhi, Software Developerhttp://www.linkedin.com/pub/uttam-gandhi/21/7aa/24 Content last revised on 1/4/13
  • 40. map::operator[] and map-insert 2/2—  Update ¡  m[k] = v; ÷  Requires no object creation, deletion ¡  m.insert( IntWidgetMap::value_type(k, v)).first->second = v; ÷  Temporary object of Widget is create, destroyedUttam Gandhi, Software Developerhttp://www.linkedin.com/pub/uttam-gandhi/21/7aa/24 Content last revised on 1/4/13
  • 41. Iterators—  Prefer iterator over const_iterator ¡  Many functions use iterator ¡  iterator insert(iterator position, const T& x); ¡  iterator erase(iterator position); ¡  iterator erase(iterator rangeBegin, iterator rangeEnd);—  ConversionsUttam Gandhi, Software Developerhttp://www.linkedin.com/pub/uttam-gandhi/21/7aa/24 Content last revised on 1/4/13
  • 42. const_iterator to iterator 1/2Uttam Gandhi, Software Developerhttp://www.linkedin.com/pub/uttam-gandhi/21/7aa/24 Content last revised on 1/4/13
  • 43. const_iterator to iterator 2/2—  It won’t compile ¡  Distance(InputIterator it1, InputIterator it2) ¡  Cannot accept two different types ¡  Need to specify type of template ¡  advance(i, distance<ConstIter>(i, ci));—  Efficiency ¡  For random access iterators in vector, string, deque – const ¡  For others its linear—  Read unformatted char data ifstream inputFile("interestingData.txt"); string fileData((istreambuf_iterator<char>(inputFile)), istreambuf_iterator<char>());Uttam Gandhi, Software Developerhttp://www.linkedin.com/pub/uttam-gandhi/21/7aa/24 Content last revised on 1/4/13
  • 44. Destination Range should be big enough 1/3Uttam Gandhi, Software Developerhttp://www.linkedin.com/pub/uttam-gandhi/21/7aa/24 Content last revised on 1/4/13
  • 45. Destination Range should be big enough 2/3Uttam Gandhi, Software Developerhttp://www.linkedin.com/pub/uttam-gandhi/21/7aa/24 Content last revised on 1/4/13
  • 46. Destination Range should be big enough 3/3—  back_inserter, calls push_back ¡  Works with sequence container (vector, list, string deque)—  front_inserter can also be used ¡  List, deque—  Inserter ¡  Insert at specified positionUttam Gandhi, Software Developerhttp://www.linkedin.com/pub/uttam-gandhi/21/7aa/24 Content last revised on 1/4/13
  • 47. Sorting Options 1/3—  Applicable on sequence containers ¡  vector, deque, string, array—  sort and stable_sort ¡  stable_sort maintains position of equivalent elements—  partial_sort ¡  e.g. Get best 20 widgets sorted—  nth element ¡  e.g. Get best 20 widgets, in any order—  partition/stable_partition ¡  Partition on a criterionUttam Gandhi, Software Developerhttp://www.linkedin.com/pub/uttam-gandhi/21/7aa/24 Content last revised on 1/4/13
  • 48. Sorting Options 2/3Uttam Gandhi, Software Developerhttp://www.linkedin.com/pub/uttam-gandhi/21/7aa/24 Content last revised on 1/4/13
  • 49. Sorting Options 3/3Uttam Gandhi, Software Developerhttp://www.linkedin.com/pub/uttam-gandhi/21/7aa/24 Content last revised on 1/4/13
  • 50. Remove algorithm on container of pointersUttam Gandhi, Software Developerhttp://www.linkedin.com/pub/uttam-gandhi/21/7aa/24 Content last revised on 1/4/13
  • 51. After remove is calledUttam Gandhi, Software Developerhttp://www.linkedin.com/pub/uttam-gandhi/21/7aa/24 Content last revised on 1/4/13
  • 52. After erase is calledUttam Gandhi, Software Developerhttp://www.linkedin.com/pub/uttam-gandhi/21/7aa/24 Content last revised on 1/4/13
  • 53. Algorithms expecting sorted ranges—  binary search algorithms ¡  binary_search ¡  lower_bound ¡  upper_bound ¡  equal_range—  Set Operations ¡  set_union ¡  set_intersection ¡  set_difference ¡  set_symmetric_difference—  Mege Sorted Ranges ¡  merge ¡  implace_merge—  Includes ¡  Check if range is present in other range—  unique—  unique_copyUttam Gandhi, Software Developerhttp://www.linkedin.com/pub/uttam-gandhi/21/7aa/24 Content last revised on 1/4/13
  • 54. Use same algo for sort and searchUttam Gandhi, Software Developerhttp://www.linkedin.com/pub/uttam-gandhi/21/7aa/24 Content last revised on 1/4/13
  • 55. Copy_if implementedUttam Gandhi, Software Developerhttp://www.linkedin.com/pub/uttam-gandhi/21/7aa/24 Content last revised on 1/4/13
  • 56. Function Objects—  Passed by value ¡  Should be small ¡  Monomorphic (non-polymorphic)Uttam Gandhi, Software Developerhttp://www.linkedin.com/pub/uttam-gandhi/21/7aa/24 Content last revised on 1/4/13
  • 57. Make functors adaptableUttam Gandhi, Software Developerhttp://www.linkedin.com/pub/uttam-gandhi/21/7aa/24 Content last revised on 1/4/13
  • 58. ptr_funUttam Gandhi, Software Developerhttp://www.linkedin.com/pub/uttam-gandhi/21/7aa/24 Content last revised on 1/4/13
  • 59. Adaptable FunctorsUttam Gandhi, Software Developerhttp://www.linkedin.com/pub/uttam-gandhi/21/7aa/24 Content last revised on 1/4/13
  • 60. not1 and bind2ndUttam Gandhi, Software Developerhttp://www.linkedin.com/pub/uttam-gandhi/21/7aa/24 Content last revised on 1/4/13
  • 61. ptr_fun, mem_fun and mem_fun_ref—  3 ways to call C++ functionUttam Gandhi, Software Developerhttp://www.linkedin.com/pub/uttam-gandhi/21/7aa/24 Content last revised on 1/4/13
  • 62. for_each usageUttam Gandhi, Software Developerhttp://www.linkedin.com/pub/uttam-gandhi/21/7aa/24 Content last revised on 1/4/13
  • 63. for_each implementation—  for_each is written in a way, its only compatible with call#1Uttam Gandhi, Software Developerhttp://www.linkedin.com/pub/uttam-gandhi/21/7aa/24 Content last revised on 1/4/13
  • 64. mem_fun exampleUttam Gandhi, Software Developerhttp://www.linkedin.com/pub/uttam-gandhi/21/7aa/24 Content last revised on 1/4/13
  • 65. Prefer algorithm to hand-written loop 1/2—  Efficiency ¡  Algorithms are often more efficient than the loops programmers produce.—  Correctness ¡  Writing loops is more subject to errors than is calling algorithms.—  Maintainability ¡  Algorithm calls often yield code that is clearer and more straightforward than the corresponding explicit loops.Uttam Gandhi, Software Developerhttp://www.linkedin.com/pub/uttam-gandhi/21/7aa/24 Content last revised on 1/4/13
  • 66. Prefer algorithm to hand-written loop 2/2—  Efficiency ¡  Check of end() is done only once ¡  Call to begin, end are generally inlined inside for_each ¡  Have knowledge about internal implementation of container ÷  E.g. using pointers for vector traversal ¡  Implementers use more sophisticated algo than avg c++ programmerUttam Gandhi, Software Developerhttp://www.linkedin.com/pub/uttam-gandhi/21/7aa/24 Content last revised on 1/4/13
  • 67. Prefer member function to algorithm 1/2—  Why ¡  Member functions are faster ¡  They integrate better with container(especially associative)—  ExampleUttam Gandhi, Software Developerhttp://www.linkedin.com/pub/uttam-gandhi/21/7aa/24 Content last revised on 1/4/13
  • 68. Prefer member function to algorithm 2/2 ¡  Member find: About 40 (worst case) to about 20 (average case) ¡  Algorithm find: 1 ,000,000 (worst case) to 500,000 (average case)—  Equivalence and eqality ¡  std::find uses equality, set::find uses equivalence—  list functions ¡  remove, remove_if. unique, sort, merge, and reverse ¡  each std version copy objects ¡  list members do not copy objects ¡  remove_erase is needed if std version used, list::remove works directlyUttam Gandhi, Software Developerhttp://www.linkedin.com/pub/uttam-gandhi/21/7aa/24 Content last revised on 1/4/13
  • 69. Search options 1/2—  Logarithmic complexity ¡  binary_search ¡  lower_bound ¡  upper_bound ¡  equal_range ¡  Uses equivalence—  Linear Search Complexity ¡  find ¡  count ¡  Use equalityUttam Gandhi, Software Developerhttp://www.linkedin.com/pub/uttam-gandhi/21/7aa/24 Content last revised on 1/4/13
  • 70. Search options 2/2—  find v/s count ¡  find stops at match of value ¡  count looks till end ¡  find is efficient for check of existence—  binary_search ¡  Widget w; //value to search for ¡  if (binary_search(vw.begin(), vw.end(), w))—  lower_bound ¡  Returns iterators to first match, if not found returns position, where the element should be insertedUttam Gandhi, Software Developerhttp://www.linkedin.com/pub/uttam-gandhi/21/7aa/24 Content last revised on 1/4/13
  • 71. equal_range—  equal_range ¡  Returns pair of iterator pointing to first and last occurrence of match ¡  If not found, both iterator return same position, where the element should be insertedUttam Gandhi, Software Developerhttp://www.linkedin.com/pub/uttam-gandhi/21/7aa/24 Content last revised on 1/4/13
  • 72. lower_bound v/s upper_boundUttam Gandhi, Software Developerhttp://www.linkedin.com/pub/uttam-gandhi/21/7aa/24 Content last revised on 1/4/13
  • 73. Use functor over functionsUttam Gandhi, Software Developerhttp://www.linkedin.com/pub/uttam-gandhi/21/7aa/24 Content last revised on 1/4/13
  • 74. Function v/s Functor performance—  Function v/s functor performance ¡  Functor version was 50% to 160% efficient than function ¡  This is because of inlining ¡  std::sort beats C qsort ÷  Sorting of a vector of million doubles was 670% fasterUttam Gandhi, Software Developerhttp://www.linkedin.com/pub/uttam-gandhi/21/7aa/24 Content last revised on 1/4/13
  • 75. Write – only code—  get rid of all the elements in the vector whose value is less than x, except that elements preceding the last occurrence of a value at least as big as y should be retainedUttam Gandhi, Software Developerhttp://www.linkedin.com/pub/uttam-gandhi/21/7aa/24 Content last revised on 1/4/13
  • 76. Make it simple—  v.f1 (f2(f3(v.f4(), v.f5(), f6(f7(), y)),.f8(), v.f9(), f6(f10(), x)), v.f9());Uttam Gandhi, Software Developerhttp://www.linkedin.com/pub/uttam-gandhi/21/7aa/24 Content last revised on 1/4/13