SlideShare una empresa de Scribd logo
1 de 77
Descargar para leer sin conexión
Effective STL Notes

     UTTAM GANDHI,
  SOFTWARE DEVELOPER
Pre-requisites

—  C++
—  Data Structure
—  Templates
—  Smart Pointers
—  Constant Time, Logarithmic, Linear




Uttam Gandhi, Software Developer
http://www.linkedin.com/pub/uttam-gandhi/21/7aa/24   Content last revised on 1/4/13
Acknowledgments

—  This presentation is based on Scott Meyers well
   known book ‘Effective STL’




Uttam Gandhi, Software Developer
http://www.linkedin.com/pub/uttam-gandhi/21/7aa/24   Content last revised on 1/4/13
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.html


Uttam Gandhi, Software Developer
http://www.linkedin.com/pub/uttam-gandhi/21/7aa/24   Content last revised on 1/4/13
STL Intro duction

—  STL consists of
    ¡  Containers

    ¡  Algorithms

    ¡  Iterators




Uttam Gandhi, Software Developer
http://www.linkedin.com/pub/uttam-gandhi/21/7aa/24   Content last revised on 1/4/13
Containers

—  Types of container
    ¡  Sequence containers
         ÷  vector
         ÷  list
         ÷  string
         ÷  deque
   ¡    Associative Containers
         ÷  set
         ÷  multiset
         ÷  map
         ÷  multimap
         ÷  unordered_map         (C++ 11)

Uttam Gandhi, Software Developer
http://www.linkedin.com/pub/uttam-gandhi/21/7aa/24   Content last revised on 1/4/13
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 containers




Uttam Gandhi, Software Developer
http://www.linkedin.com/pub/uttam-gandhi/21/7aa/24   Content last revised on 1/4/13
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 counting



Uttam Gandhi, Software Developer
http://www.linkedin.com/pub/uttam-gandhi/21/7aa/24   Content last revised on 1/4/13
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 slicing


Uttam Gandhi, Software Developer
http://www.linkedin.com/pub/uttam-gandhi/21/7aa/24   Content last revised on 1/4/13
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 Developer
http://www.linkedin.com/pub/uttam-gandhi/21/7aa/24   Content last revised on 1/4/13
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 constant



Uttam Gandhi, Software Developer
http://www.linkedin.com/pub/uttam-gandhi/21/7aa/24   Content last revised on 1/4/13
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 understand

Uttam Gandhi, Software Developer
http://www.linkedin.com/pub/uttam-gandhi/21/7aa/24   Content last revised on 1/4/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
             constructor

Uttam Gandhi, Software Developer
http://www.linkedin.com/pub/uttam-gandhi/21/7aa/24   Content last revised on 1/4/13
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
           allocations




Uttam Gandhi, Software Developer
http://www.linkedin.com/pub/uttam-gandhi/21/7aa/24   Content last revised on 1/4/13
Use delete for new element in container 1/3

void doSomething()
{
vector<Widget*> vwp;
for (int i = 0; i < SOME_MAGIC_NUMBER; ++i)
vwp.push_back(new Widget);
… // use vwp
}
This is a leak

Uttam Gandhi, Software Developer
http://www.linkedin.com/pub/uttam-gandhi/21/7aa/24   Content last revised on 1/4/13
Use delete for new element in container 2/3

void doSomething()
{
vector<Widget*> vwp;
… // as before
for (vector<Widget*>::iterator i = vwp.begin();
i != vwp.end(),
++i) {
delete *i;
} still there can be leak because of exception
Uttam Gandhi, Software Developer
http://www.linkedin.com/pub/uttam-gandhi/21/7aa/24   Content last revised on 1/4/13
Use delete for new element in container 3/3

void 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 above
Uttam Gandhi, Software Developer
http://www.linkedin.com/pub/uttam-gandhi/21/7aa/24   Content last revised on 1/4/13
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 time




Uttam Gandhi, Software Developer
http://www.linkedin.com/pub/uttam-gandhi/21/7aa/24   Content last revised on 1/4/13
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 erase
AssocContainer<int> c;
......
for (AssocContainer<int>::iterator i = c.begin();
i!= c.end(); ++i) {
if (badValue(*i)) c.erase(i);
}


Uttam Gandhi, Software Developer
http://www.linkedin.com/pub/uttam-gandhi/21/7aa/24            Content last revised on 1/4/13
Choosing Erasing Options

AssocContainer<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 invalidating



Uttam Gandhi, Software Developer
http://www.linkedin.com/pub/uttam-gandhi/21/7aa/24   Content last revised on 1/4/13
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.htm
Uttam Gandhi, Software Developer
http://www.linkedin.com/pub/uttam-gandhi/21/7aa/24   Content last revised on 1/4/13
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 reserve




Uttam Gandhi, Software Developer
http://www.linkedin.com/pub/uttam-gandhi/21/7aa/24   Content last revised on 1/4/13
Pass vector and string to legacy API

—  Vector
    ¡  void doSomething(const int* pInts, size_t numlnts);

    ¡  doSomething(&v[0], v.size());

    ¡  Frankly, if you're 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 Developer
http://www.linkedin.com/pub/uttam-gandhi/21/7aa/24   Content last revised on 1/4/13
Pass vector and string to legacy API

—  String
    ¡  void doSomething(const char *pString);

    ¡  doSomething(s.c_str());




Uttam Gandhi, Software Developer
http://www.linkedin.com/pub/uttam-gandhi/21/7aa/24   Content last revised on 1/4/13
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 destroyed



Uttam Gandhi, Software Developer
http://www.linkedin.com/pub/uttam-gandhi/21/7aa/24   Content last revised on 1/4/13
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 Developer
http://www.linkedin.com/pub/uttam-gandhi/21/7aa/24   Content last revised on 1/4/13
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 Developer
http://www.linkedin.com/pub/uttam-gandhi/21/7aa/24   Content last revised on 1/4/13
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 case
Uttam Gandhi, Software Developer
http://www.linkedin.com/pub/uttam-gandhi/21/7aa/24   Content last revised on 1/4/13
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 Developer
http://www.linkedin.com/pub/uttam-gandhi/21/7aa/24   Content last revised on 1/4/13
Functor for string dereference

struct StringPtrLess: public binary_function<const
string*, 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 Developer
http://www.linkedin.com/pub/uttam-gandhi/21/7aa/24   Content last revised on 1/4/13
Templatized functor for de-reference

struct DereferenceLess {
template <typename PtrType>
bool operator()(PtrType pT1, PtrType pT2) const
value, because we expect them
{
return *pT1 < *pT2;
}
};


Uttam Gandhi, Software Developer
http://www.linkedin.com/pub/uttam-gandhi/21/7aa/24   Content last revised on 1/4/13
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 equivalent




Uttam Gandhi, Software Developer
http://www.linkedin.com/pub/uttam-gandhi/21/7aa/24   Content last revised on 1/4/13
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, we'll get back a pair of iterators that define a
       range containing both copies
   ¡  equal_range identifies a range of equivalent values




Uttam Gandhi, Software Developer
http://www.linkedin.com/pub/uttam-gandhi/21/7aa/24   Content last revised on 1/4/13
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 corrupt




Uttam Gandhi, Software Developer
http://www.linkedin.com/pub/uttam-gandhi/21/7aa/24   Content last revised on 1/4/13
In-place modification of set/multiset value2/2




Uttam Gandhi, Software Developer
http://www.linkedin.com/pub/uttam-gandhi/21/7aa/24   Content last revised on 1/4/13
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, sort
Uttam Gandhi, Software Developer
http://www.linkedin.com/pub/uttam-gandhi/21/7aa/24   Content last revised on 1/4/13
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 these




Uttam Gandhi, Software Developer
http://www.linkedin.com/pub/uttam-gandhi/21/7aa/24   Content last revised on 1/4/13
Sorted vector v/s associative container 3/3




Uttam Gandhi, Software Developer
http://www.linkedin.com/pub/uttam-gandhi/21/7aa/24   Content last revised on 1/4/13
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 saved



Uttam Gandhi, Software Developer
http://www.linkedin.com/pub/uttam-gandhi/21/7aa/24   Content last revised on 1/4/13
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, destroyed




Uttam Gandhi, Software Developer
http://www.linkedin.com/pub/uttam-gandhi/21/7aa/24     Content last revised on 1/4/13
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);

—  Conversions




Uttam Gandhi, Software Developer
http://www.linkedin.com/pub/uttam-gandhi/21/7aa/24   Content last revised on 1/4/13
const_iterator to iterator 1/2




Uttam Gandhi, Software Developer
http://www.linkedin.com/pub/uttam-gandhi/21/7aa/24   Content last revised on 1/4/13
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 Developer
http://www.linkedin.com/pub/uttam-gandhi/21/7aa/24   Content last revised on 1/4/13
Destination Range should be big enough 1/3




Uttam Gandhi, Software Developer
http://www.linkedin.com/pub/uttam-gandhi/21/7aa/24   Content last revised on 1/4/13
Destination Range should be big enough 2/3




Uttam Gandhi, Software Developer
http://www.linkedin.com/pub/uttam-gandhi/21/7aa/24   Content last revised on 1/4/13
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 position




Uttam Gandhi, Software Developer
http://www.linkedin.com/pub/uttam-gandhi/21/7aa/24   Content last revised on 1/4/13
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 criterion

Uttam Gandhi, Software Developer
http://www.linkedin.com/pub/uttam-gandhi/21/7aa/24   Content last revised on 1/4/13
Sorting Options 2/3




Uttam Gandhi, Software Developer
http://www.linkedin.com/pub/uttam-gandhi/21/7aa/24   Content last revised on 1/4/13
Sorting Options 3/3




Uttam Gandhi, Software Developer
http://www.linkedin.com/pub/uttam-gandhi/21/7aa/24   Content last revised on 1/4/13
Remove algorithm on container of pointers




Uttam Gandhi, Software Developer
http://www.linkedin.com/pub/uttam-gandhi/21/7aa/24   Content last revised on 1/4/13
After remove is called




Uttam Gandhi, Software Developer
http://www.linkedin.com/pub/uttam-gandhi/21/7aa/24   Content last revised on 1/4/13
After erase is called




Uttam Gandhi, Software Developer
http://www.linkedin.com/pub/uttam-gandhi/21/7aa/24   Content last revised on 1/4/13
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_copy


Uttam Gandhi, Software Developer
http://www.linkedin.com/pub/uttam-gandhi/21/7aa/24   Content last revised on 1/4/13
Use same algo for sort and search




Uttam Gandhi, Software Developer
http://www.linkedin.com/pub/uttam-gandhi/21/7aa/24   Content last revised on 1/4/13
Copy_if implemented




Uttam Gandhi, Software Developer
http://www.linkedin.com/pub/uttam-gandhi/21/7aa/24   Content last revised on 1/4/13
Function Objects

—  Passed by value
    ¡  Should be small

    ¡  Monomorphic (non-polymorphic)




Uttam Gandhi, Software Developer
http://www.linkedin.com/pub/uttam-gandhi/21/7aa/24   Content last revised on 1/4/13
Make functors adaptable




Uttam Gandhi, Software Developer
http://www.linkedin.com/pub/uttam-gandhi/21/7aa/24   Content last revised on 1/4/13
ptr_fun




Uttam Gandhi, Software Developer
http://www.linkedin.com/pub/uttam-gandhi/21/7aa/24     Content last revised on 1/4/13
Adaptable Functors




Uttam Gandhi, Software Developer
http://www.linkedin.com/pub/uttam-gandhi/21/7aa/24   Content last revised on 1/4/13
not1 and bind2nd




Uttam Gandhi, Software Developer
http://www.linkedin.com/pub/uttam-gandhi/21/7aa/24   Content last revised on 1/4/13
ptr_fun, mem_fun and mem_fun_ref

—  3 ways to call C++ function




Uttam Gandhi, Software Developer
http://www.linkedin.com/pub/uttam-gandhi/21/7aa/24   Content last revised on 1/4/13
for_each usage




Uttam Gandhi, Software Developer
http://www.linkedin.com/pub/uttam-gandhi/21/7aa/24   Content last revised on 1/4/13
for_each implementation

—  for_each is written in a way, its only compatible with
   call#1




Uttam Gandhi, Software Developer
http://www.linkedin.com/pub/uttam-gandhi/21/7aa/24   Content last revised on 1/4/13
mem_fun example




Uttam Gandhi, Software Developer
http://www.linkedin.com/pub/uttam-gandhi/21/7aa/24   Content last revised on 1/4/13
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 Developer
http://www.linkedin.com/pub/uttam-gandhi/21/7aa/24   Content last revised on 1/4/13
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++
         programmer




Uttam Gandhi, Software Developer
http://www.linkedin.com/pub/uttam-gandhi/21/7aa/24   Content last revised on 1/4/13
Prefer member function to algorithm 1/2

—  Why
    ¡  Member functions are faster

    ¡  They integrate better with container(especially associative)

—  Example




Uttam Gandhi, Software Developer
http://www.linkedin.com/pub/uttam-gandhi/21/7aa/24   Content last revised on 1/4/13
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
        directly
Uttam Gandhi, Software Developer
http://www.linkedin.com/pub/uttam-gandhi/21/7aa/24   Content last revised on 1/4/13
Search options 1/2

—  Logarithmic complexity
    ¡  binary_search

    ¡  lower_bound

    ¡  upper_bound

    ¡  equal_range

    ¡  Uses equivalence

—  Linear Search Complexity
    ¡  find

    ¡  count

    ¡  Use equality


Uttam Gandhi, Software Developer
http://www.linkedin.com/pub/uttam-gandhi/21/7aa/24   Content last revised on 1/4/13
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 inserted

Uttam Gandhi, Software Developer
http://www.linkedin.com/pub/uttam-gandhi/21/7aa/24   Content last revised on 1/4/13
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 inserted




Uttam Gandhi, Software Developer
http://www.linkedin.com/pub/uttam-gandhi/21/7aa/24   Content last revised on 1/4/13
lower_bound v/s upper_bound




Uttam Gandhi, Software Developer
http://www.linkedin.com/pub/uttam-gandhi/21/7aa/24   Content last revised on 1/4/13
Use functor over functions




Uttam Gandhi, Software Developer
http://www.linkedin.com/pub/uttam-gandhi/21/7aa/24   Content last revised on 1/4/13
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% faster




Uttam Gandhi, Software Developer
http://www.linkedin.com/pub/uttam-gandhi/21/7aa/24   Content last revised on 1/4/13
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
   retained




Uttam Gandhi, Software Developer
http://www.linkedin.com/pub/uttam-gandhi/21/7aa/24   Content last revised on 1/4/13
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 Developer
http://www.linkedin.com/pub/uttam-gandhi/21/7aa/24   Content last revised on 1/4/13

Más contenido relacionado

La actualidad más candente

Qcon2011 functions rockpresentation_scala
Qcon2011 functions rockpresentation_scalaQcon2011 functions rockpresentation_scala
Qcon2011 functions rockpresentation_scalaMichael Stal
 
(7) c sharp introduction_advanvced_features_part_ii
(7) c sharp introduction_advanvced_features_part_ii(7) c sharp introduction_advanvced_features_part_ii
(7) c sharp introduction_advanvced_features_part_iiNico Ludwig
 
Aggregate Programming in Scala
Aggregate Programming in ScalaAggregate Programming in Scala
Aggregate Programming in ScalaRoberto Casadei
 
JavaScript: Patterns, Part 3
JavaScript: Patterns, Part  3JavaScript: Patterns, Part  3
JavaScript: Patterns, Part 3Chris Farrell
 
JavaScript Object Oriented Programming Cheat Sheet
JavaScript Object Oriented Programming Cheat SheetJavaScript Object Oriented Programming Cheat Sheet
JavaScript Object Oriented Programming Cheat SheetHDR1001
 
Introduction to Object Oriented Javascript
Introduction to Object Oriented JavascriptIntroduction to Object Oriented Javascript
Introduction to Object Oriented Javascriptnodeninjas
 
A Brief Conceptual Introduction to Functional Java 8 and its API
A Brief Conceptual Introduction to Functional Java 8 and its APIA Brief Conceptual Introduction to Functional Java 8 and its API
A Brief Conceptual Introduction to Functional Java 8 and its APIJörn Guy Süß JGS
 
FregeDay: Design and Implementation of the language (Ingo Wechsung)
FregeDay: Design and Implementation of the language (Ingo Wechsung)FregeDay: Design and Implementation of the language (Ingo Wechsung)
FregeDay: Design and Implementation of the language (Ingo Wechsung)Dierk König
 
New c sharp3_features_(linq)_part_ii
New c sharp3_features_(linq)_part_iiNew c sharp3_features_(linq)_part_ii
New c sharp3_features_(linq)_part_iiNico Ludwig
 
Swift Tutorial Part 1. The Complete Guide For Swift Programming Language
Swift Tutorial Part 1. The Complete Guide For Swift Programming LanguageSwift Tutorial Part 1. The Complete Guide For Swift Programming Language
Swift Tutorial Part 1. The Complete Guide For Swift Programming LanguageHossam Ghareeb
 
Effective c# part1
Effective c# part1Effective c# part1
Effective c# part1Yuriy Seniuk
 
C++ vs C#
C++ vs C#C++ vs C#
C++ vs C#sudipv
 
C++ unit-1-part-9
C++ unit-1-part-9C++ unit-1-part-9
C++ unit-1-part-9Jadavsejal
 
Oop lec 5-(class objects, constructor & destructor)
Oop lec 5-(class objects, constructor & destructor)Oop lec 5-(class objects, constructor & destructor)
Oop lec 5-(class objects, constructor & destructor)Asfand Hassan
 

La actualidad más candente (20)

Qcon2011 functions rockpresentation_scala
Qcon2011 functions rockpresentation_scalaQcon2011 functions rockpresentation_scala
Qcon2011 functions rockpresentation_scala
 
(7) c sharp introduction_advanvced_features_part_ii
(7) c sharp introduction_advanvced_features_part_ii(7) c sharp introduction_advanvced_features_part_ii
(7) c sharp introduction_advanvced_features_part_ii
 
Aggregate Programming in Scala
Aggregate Programming in ScalaAggregate Programming in Scala
Aggregate Programming in Scala
 
C tour Unix
C tour UnixC tour Unix
C tour Unix
 
JavaScript: Patterns, Part 3
JavaScript: Patterns, Part  3JavaScript: Patterns, Part  3
JavaScript: Patterns, Part 3
 
JavaScript Object Oriented Programming Cheat Sheet
JavaScript Object Oriented Programming Cheat SheetJavaScript Object Oriented Programming Cheat Sheet
JavaScript Object Oriented Programming Cheat Sheet
 
Introduction to Object Oriented Javascript
Introduction to Object Oriented JavascriptIntroduction to Object Oriented Javascript
Introduction to Object Oriented Javascript
 
Constructors and Destructors
Constructors and DestructorsConstructors and Destructors
Constructors and Destructors
 
Client sidescripting javascript
Client sidescripting javascriptClient sidescripting javascript
Client sidescripting javascript
 
A Brief Conceptual Introduction to Functional Java 8 and its API
A Brief Conceptual Introduction to Functional Java 8 and its APIA Brief Conceptual Introduction to Functional Java 8 and its API
A Brief Conceptual Introduction to Functional Java 8 and its API
 
Thinking in Functions
Thinking in FunctionsThinking in Functions
Thinking in Functions
 
FregeDay: Design and Implementation of the language (Ingo Wechsung)
FregeDay: Design and Implementation of the language (Ingo Wechsung)FregeDay: Design and Implementation of the language (Ingo Wechsung)
FregeDay: Design and Implementation of the language (Ingo Wechsung)
 
New c sharp3_features_(linq)_part_ii
New c sharp3_features_(linq)_part_iiNew c sharp3_features_(linq)_part_ii
New c sharp3_features_(linq)_part_ii
 
Swift Tutorial Part 1. The Complete Guide For Swift Programming Language
Swift Tutorial Part 1. The Complete Guide For Swift Programming LanguageSwift Tutorial Part 1. The Complete Guide For Swift Programming Language
Swift Tutorial Part 1. The Complete Guide For Swift Programming Language
 
Effective c# part1
Effective c# part1Effective c# part1
Effective c# part1
 
C++ vs C#
C++ vs C#C++ vs C#
C++ vs C#
 
C++ unit-1-part-9
C++ unit-1-part-9C++ unit-1-part-9
C++ unit-1-part-9
 
Oop lec 5-(class objects, constructor & destructor)
Oop lec 5-(class objects, constructor & destructor)Oop lec 5-(class objects, constructor & destructor)
Oop lec 5-(class objects, constructor & destructor)
 
Type Casting in C++
Type Casting in C++Type Casting in C++
Type Casting in C++
 
C#4.0 features
C#4.0 featuresC#4.0 features
C#4.0 features
 

Destacado

C traps and pitfalls for C++ programmers
C traps and pitfalls for C++ programmersC traps and pitfalls for C++ programmers
C traps and pitfalls for C++ programmersRichard Thomson
 
Статический и динамический полиморфизм в C++, Дмитрий Леванов
Статический и динамический полиморфизм в C++, Дмитрий ЛевановСтатический и динамический полиморфизм в C++, Дмитрий Леванов
Статический и динамический полиморфизм в C++, Дмитрий ЛевановYandex
 
High Order Function Computations in c++14 (C++ Dev Meetup Iasi)
High Order Function Computations in c++14 (C++ Dev Meetup Iasi)High Order Function Computations in c++14 (C++ Dev Meetup Iasi)
High Order Function Computations in c++14 (C++ Dev Meetup Iasi)Ovidiu Farauanu
 
Dependency Injection in C++ (Community Days 2015)
Dependency Injection in C++ (Community Days 2015)Dependency Injection in C++ (Community Days 2015)
Dependency Injection in C++ (Community Days 2015)Daniele Pallastrelli
 
С++ without new and delete
С++ without new and deleteС++ without new and delete
С++ without new and deletePlatonov Sergey
 
Михаил Матросов, “С++ без new и delete”
Михаил Матросов, “С++ без new и delete”Михаил Матросов, “С++ без new и delete”
Михаил Матросов, “С++ без new и delete”Platonov Sergey
 
Memory Management C++ (Peeling operator new() and delete())
Memory Management C++ (Peeling operator new() and delete())Memory Management C++ (Peeling operator new() and delete())
Memory Management C++ (Peeling operator new() and delete())Sameer Rathoud
 
Operator Overloading
Operator OverloadingOperator Overloading
Operator OverloadingDustin Chase
 
Multithreading 101
Multithreading 101Multithreading 101
Multithreading 101Tim Penhey
 
C++ Dependency Management 2.0
C++ Dependency Management 2.0C++ Dependency Management 2.0
C++ Dependency Management 2.0Patrick Charrier
 
C++ Memory Management
C++ Memory ManagementC++ Memory Management
C++ Memory ManagementAnil Bapat
 
C++11 smart pointers
C++11 smart pointersC++11 smart pointers
C++11 smart pointerschchwy Chang
 
Operator overloading
Operator overloadingOperator overloading
Operator overloadingKamal Acharya
 
Introduction to Bitcoin and ECDSA
Introduction to Bitcoin and ECDSAIntroduction to Bitcoin and ECDSA
Introduction to Bitcoin and ECDSANikesh Mistry
 
Multithreading done right
Multithreading done rightMultithreading done right
Multithreading done rightPlatonov Sergey
 

Destacado (20)

Modern C++
Modern C++Modern C++
Modern C++
 
C traps and pitfalls for C++ programmers
C traps and pitfalls for C++ programmersC traps and pitfalls for C++ programmers
C traps and pitfalls for C++ programmers
 
Smart Pointers
Smart PointersSmart Pointers
Smart Pointers
 
Статический и динамический полиморфизм в C++, Дмитрий Леванов
Статический и динамический полиморфизм в C++, Дмитрий ЛевановСтатический и динамический полиморфизм в C++, Дмитрий Леванов
Статический и динамический полиморфизм в C++, Дмитрий Леванов
 
High Order Function Computations in c++14 (C++ Dev Meetup Iasi)
High Order Function Computations in c++14 (C++ Dev Meetup Iasi)High Order Function Computations in c++14 (C++ Dev Meetup Iasi)
High Order Function Computations in c++14 (C++ Dev Meetup Iasi)
 
Dependency Injection in C++ (Community Days 2015)
Dependency Injection in C++ (Community Days 2015)Dependency Injection in C++ (Community Days 2015)
Dependency Injection in C++ (Community Days 2015)
 
С++ without new and delete
С++ without new and deleteС++ without new and delete
С++ without new and delete
 
Михаил Матросов, “С++ без new и delete”
Михаил Матросов, “С++ без new и delete”Михаил Матросов, “С++ без new и delete”
Михаил Матросов, “С++ без new и delete”
 
Memory Management C++ (Peeling operator new() and delete())
Memory Management C++ (Peeling operator new() and delete())Memory Management C++ (Peeling operator new() and delete())
Memory Management C++ (Peeling operator new() and delete())
 
Operator Overloading
Operator OverloadingOperator Overloading
Operator Overloading
 
Multithreading 101
Multithreading 101Multithreading 101
Multithreading 101
 
STL Algorithms In Action
STL Algorithms In ActionSTL Algorithms In Action
STL Algorithms In Action
 
C++ Dependency Management 2.0
C++ Dependency Management 2.0C++ Dependency Management 2.0
C++ Dependency Management 2.0
 
C++ Memory Management
C++ Memory ManagementC++ Memory Management
C++ Memory Management
 
File Pointers
File PointersFile Pointers
File Pointers
 
C++11 smart pointers
C++11 smart pointersC++11 smart pointers
C++11 smart pointers
 
Memory Management In C++
Memory Management In C++Memory Management In C++
Memory Management In C++
 
Operator overloading
Operator overloadingOperator overloading
Operator overloading
 
Introduction to Bitcoin and ECDSA
Introduction to Bitcoin and ECDSAIntroduction to Bitcoin and ECDSA
Introduction to Bitcoin and ECDSA
 
Multithreading done right
Multithreading done rightMultithreading done right
Multithreading done right
 

Similar a Effective stl notes

High Performance Ajax Applications 1197671494632682 2
High Performance Ajax Applications 1197671494632682 2High Performance Ajax Applications 1197671494632682 2
High Performance Ajax Applications 1197671494632682 2Niti Chotkaew
 
High Performance Ajax Applications
High Performance Ajax ApplicationsHigh Performance Ajax Applications
High Performance Ajax ApplicationsJulien Lecomte
 
Angular performance slides
Angular performance slidesAngular performance slides
Angular performance slidesDavid Barreto
 
Developing and Benchmarking Qt applications on Hawkboard with Xgxperf
Developing and Benchmarking Qt applications on Hawkboard with XgxperfDeveloping and Benchmarking Qt applications on Hawkboard with Xgxperf
Developing and Benchmarking Qt applications on Hawkboard with XgxperfPrabindh Sundareson
 
Java programming concept
Java programming conceptJava programming concept
Java programming conceptSanjay Gunjal
 
Front End Development for Back End Developers - UberConf 2017
Front End Development for Back End Developers - UberConf 2017Front End Development for Back End Developers - UberConf 2017
Front End Development for Back End Developers - UberConf 2017Matt Raible
 
ScalaUA - distage: Staged Dependency Injection
ScalaUA - distage: Staged Dependency InjectionScalaUA - distage: Staged Dependency Injection
ScalaUA - distage: Staged Dependency Injection7mind
 
Angular Optimization Web Performance Meetup
Angular Optimization Web Performance MeetupAngular Optimization Web Performance Meetup
Angular Optimization Web Performance MeetupDavid Barreto
 
Tech Talk - Overview of Dash framework for building dashboards
Tech Talk - Overview of Dash framework for building dashboardsTech Talk - Overview of Dash framework for building dashboards
Tech Talk - Overview of Dash framework for building dashboardsAppsilon Data Science
 
Python Programming Essentials - M35 - Iterators & Generators
Python Programming Essentials - M35 - Iterators & GeneratorsPython Programming Essentials - M35 - Iterators & Generators
Python Programming Essentials - M35 - Iterators & GeneratorsP3 InfoTech Solutions Pvt. Ltd.
 
How to navigate programmatically using react router
How to navigate programmatically using react routerHow to navigate programmatically using react router
How to navigate programmatically using react routerBOSC Tech Labs
 
Testing of javacript
Testing of javacriptTesting of javacript
Testing of javacriptLei Kang
 
Catia product enhancement_overview_v5r20
Catia product enhancement_overview_v5r20Catia product enhancement_overview_v5r20
Catia product enhancement_overview_v5r20Jimmy Chang
 
Mobile Developer Summit 2012, Pune
Mobile Developer Summit 2012, PuneMobile Developer Summit 2012, Pune
Mobile Developer Summit 2012, PuneBhuvan Khanna
 
Whats new in ES2019
Whats new in ES2019Whats new in ES2019
Whats new in ES2019chayanikaa
 
Handling Exceptions In C &amp; C++ [Part B] Ver 2
Handling Exceptions In C &amp; C++ [Part B] Ver 2Handling Exceptions In C &amp; C++ [Part B] Ver 2
Handling Exceptions In C &amp; C++ [Part B] Ver 2ppd1961
 
Dot net guide for beginner
Dot net guide for beginner Dot net guide for beginner
Dot net guide for beginner jayc8586
 
Not Your Fathers C - C Application Development In 2016
Not Your Fathers C - C Application Development In 2016Not Your Fathers C - C Application Development In 2016
Not Your Fathers C - C Application Development In 2016maiktoepfer
 

Similar a Effective stl notes (20)

High Performance Ajax Applications 1197671494632682 2
High Performance Ajax Applications 1197671494632682 2High Performance Ajax Applications 1197671494632682 2
High Performance Ajax Applications 1197671494632682 2
 
High Performance Ajax Applications
High Performance Ajax ApplicationsHigh Performance Ajax Applications
High Performance Ajax Applications
 
Angular performance slides
Angular performance slidesAngular performance slides
Angular performance slides
 
Developing and Benchmarking Qt applications on Hawkboard with Xgxperf
Developing and Benchmarking Qt applications on Hawkboard with XgxperfDeveloping and Benchmarking Qt applications on Hawkboard with Xgxperf
Developing and Benchmarking Qt applications on Hawkboard with Xgxperf
 
Java programming concept
Java programming conceptJava programming concept
Java programming concept
 
Best practices android_2010
Best practices android_2010Best practices android_2010
Best practices android_2010
 
Front End Development for Back End Developers - UberConf 2017
Front End Development for Back End Developers - UberConf 2017Front End Development for Back End Developers - UberConf 2017
Front End Development for Back End Developers - UberConf 2017
 
ScalaUA - distage: Staged Dependency Injection
ScalaUA - distage: Staged Dependency InjectionScalaUA - distage: Staged Dependency Injection
ScalaUA - distage: Staged Dependency Injection
 
Angular Optimization Web Performance Meetup
Angular Optimization Web Performance MeetupAngular Optimization Web Performance Meetup
Angular Optimization Web Performance Meetup
 
Tech Talk - Overview of Dash framework for building dashboards
Tech Talk - Overview of Dash framework for building dashboardsTech Talk - Overview of Dash framework for building dashboards
Tech Talk - Overview of Dash framework for building dashboards
 
Python Programming Essentials - M35 - Iterators & Generators
Python Programming Essentials - M35 - Iterators & GeneratorsPython Programming Essentials - M35 - Iterators & Generators
Python Programming Essentials - M35 - Iterators & Generators
 
How to navigate programmatically using react router
How to navigate programmatically using react routerHow to navigate programmatically using react router
How to navigate programmatically using react router
 
Testing of javacript
Testing of javacriptTesting of javacript
Testing of javacript
 
Catia product enhancement_overview_v5r20
Catia product enhancement_overview_v5r20Catia product enhancement_overview_v5r20
Catia product enhancement_overview_v5r20
 
Mobile Developer Summit 2012, Pune
Mobile Developer Summit 2012, PuneMobile Developer Summit 2012, Pune
Mobile Developer Summit 2012, Pune
 
20120308 droid4me-paug presentation
20120308 droid4me-paug presentation20120308 droid4me-paug presentation
20120308 droid4me-paug presentation
 
Whats new in ES2019
Whats new in ES2019Whats new in ES2019
Whats new in ES2019
 
Handling Exceptions In C &amp; C++ [Part B] Ver 2
Handling Exceptions In C &amp; C++ [Part B] Ver 2Handling Exceptions In C &amp; C++ [Part B] Ver 2
Handling Exceptions In C &amp; C++ [Part B] Ver 2
 
Dot net guide for beginner
Dot net guide for beginner Dot net guide for beginner
Dot net guide for beginner
 
Not Your Fathers C - C Application Development In 2016
Not Your Fathers C - C Application Development In 2016Not Your Fathers C - C Application Development In 2016
Not Your Fathers C - C Application Development In 2016
 

Último

[BuildWithAI] Introduction to Gemini.pdf
[BuildWithAI] Introduction to Gemini.pdf[BuildWithAI] Introduction to Gemini.pdf
[BuildWithAI] Introduction to Gemini.pdfSandro Moreira
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerThousandEyes
 
Apidays New York 2024 - Passkeys: Developing APIs to enable passwordless auth...
Apidays New York 2024 - Passkeys: Developing APIs to enable passwordless auth...Apidays New York 2024 - Passkeys: Developing APIs to enable passwordless auth...
Apidays New York 2024 - Passkeys: Developing APIs to enable passwordless auth...apidays
 
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...Jeffrey Haguewood
 
Elevate Developer Efficiency & build GenAI Application with Amazon Q​
Elevate Developer Efficiency & build GenAI Application with Amazon Q​Elevate Developer Efficiency & build GenAI Application with Amazon Q​
Elevate Developer Efficiency & build GenAI Application with Amazon Q​Bhuvaneswari Subramani
 
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers:  A Deep Dive into Serverless Spatial Data and FMECloud Frontiers:  A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FMESafe Software
 
Artificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : UncertaintyArtificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : UncertaintyKhushali Kathiriya
 
MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 2024MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 2024MIND CTI
 
Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...
Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...
Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...apidays
 
MS Copilot expands with MS Graph connectors
MS Copilot expands with MS Graph connectorsMS Copilot expands with MS Graph connectors
MS Copilot expands with MS Graph connectorsNanddeep Nachan
 
Corporate and higher education May webinar.pptx
Corporate and higher education May webinar.pptxCorporate and higher education May webinar.pptx
Corporate and higher education May webinar.pptxRustici Software
 
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, AdobeApidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobeapidays
 
Exploring Multimodal Embeddings with Milvus
Exploring Multimodal Embeddings with MilvusExploring Multimodal Embeddings with Milvus
Exploring Multimodal Embeddings with MilvusZilliz
 
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers:  A Deep Dive into Serverless Spatial Data and FMECloud Frontiers:  A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FMESafe Software
 
Boost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfBoost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfsudhanshuwaghmare1
 
DEV meet-up UiPath Document Understanding May 7 2024 Amsterdam
DEV meet-up UiPath Document Understanding May 7 2024 AmsterdamDEV meet-up UiPath Document Understanding May 7 2024 Amsterdam
DEV meet-up UiPath Document Understanding May 7 2024 AmsterdamUiPathCommunity
 
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...apidays
 
WSO2's API Vision: Unifying Control, Empowering Developers
WSO2's API Vision: Unifying Control, Empowering DevelopersWSO2's API Vision: Unifying Control, Empowering Developers
WSO2's API Vision: Unifying Control, Empowering DevelopersWSO2
 
Finding Java's Hidden Performance Traps @ DevoxxUK 2024
Finding Java's Hidden Performance Traps @ DevoxxUK 2024Finding Java's Hidden Performance Traps @ DevoxxUK 2024
Finding Java's Hidden Performance Traps @ DevoxxUK 2024Victor Rentea
 
DBX First Quarter 2024 Investor Presentation
DBX First Quarter 2024 Investor PresentationDBX First Quarter 2024 Investor Presentation
DBX First Quarter 2024 Investor PresentationDropbox
 

Último (20)

[BuildWithAI] Introduction to Gemini.pdf
[BuildWithAI] Introduction to Gemini.pdf[BuildWithAI] Introduction to Gemini.pdf
[BuildWithAI] Introduction to Gemini.pdf
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected Worker
 
Apidays New York 2024 - Passkeys: Developing APIs to enable passwordless auth...
Apidays New York 2024 - Passkeys: Developing APIs to enable passwordless auth...Apidays New York 2024 - Passkeys: Developing APIs to enable passwordless auth...
Apidays New York 2024 - Passkeys: Developing APIs to enable passwordless auth...
 
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...
 
Elevate Developer Efficiency & build GenAI Application with Amazon Q​
Elevate Developer Efficiency & build GenAI Application with Amazon Q​Elevate Developer Efficiency & build GenAI Application with Amazon Q​
Elevate Developer Efficiency & build GenAI Application with Amazon Q​
 
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers:  A Deep Dive into Serverless Spatial Data and FMECloud Frontiers:  A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
 
Artificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : UncertaintyArtificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : Uncertainty
 
MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 2024MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 2024
 
Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...
Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...
Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...
 
MS Copilot expands with MS Graph connectors
MS Copilot expands with MS Graph connectorsMS Copilot expands with MS Graph connectors
MS Copilot expands with MS Graph connectors
 
Corporate and higher education May webinar.pptx
Corporate and higher education May webinar.pptxCorporate and higher education May webinar.pptx
Corporate and higher education May webinar.pptx
 
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, AdobeApidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
 
Exploring Multimodal Embeddings with Milvus
Exploring Multimodal Embeddings with MilvusExploring Multimodal Embeddings with Milvus
Exploring Multimodal Embeddings with Milvus
 
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers:  A Deep Dive into Serverless Spatial Data and FMECloud Frontiers:  A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
 
Boost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfBoost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdf
 
DEV meet-up UiPath Document Understanding May 7 2024 Amsterdam
DEV meet-up UiPath Document Understanding May 7 2024 AmsterdamDEV meet-up UiPath Document Understanding May 7 2024 Amsterdam
DEV meet-up UiPath Document Understanding May 7 2024 Amsterdam
 
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...
 
WSO2's API Vision: Unifying Control, Empowering Developers
WSO2's API Vision: Unifying Control, Empowering DevelopersWSO2's API Vision: Unifying Control, Empowering Developers
WSO2's API Vision: Unifying Control, Empowering Developers
 
Finding Java's Hidden Performance Traps @ DevoxxUK 2024
Finding Java's Hidden Performance Traps @ DevoxxUK 2024Finding Java's Hidden Performance Traps @ DevoxxUK 2024
Finding Java's Hidden Performance Traps @ DevoxxUK 2024
 
DBX First Quarter 2024 Investor Presentation
DBX First Quarter 2024 Investor PresentationDBX First Quarter 2024 Investor Presentation
DBX First Quarter 2024 Investor Presentation
 

Effective stl notes

  • 1. Effective STL Notes UTTAM GANDHI, SOFTWARE DEVELOPER
  • 2. Pre-requisites —  C++ —  Data Structure —  Templates —  Smart Pointers —  Constant Time, Logarithmic, Linear Uttam Gandhi, Software Developer http://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 Developer http://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.html Uttam Gandhi, Software Developer http://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 ¡  Iterators Uttam Gandhi, Software Developer http://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 Developer http://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 containers Uttam Gandhi, Software Developer http://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 counting Uttam Gandhi, Software Developer http://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 slicing Uttam Gandhi, Software Developer http://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 Developer http://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 constant Uttam Gandhi, Software Developer http://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 understand Uttam Gandhi, Software Developer http://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 constructor Uttam Gandhi, Software Developer http://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 allocations Uttam Gandhi, Software Developer http://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/3 void doSomething() { vector<Widget*> vwp; for (int i = 0; i < SOME_MAGIC_NUMBER; ++i) vwp.push_back(new Widget); … // use vwp } This is a leak Uttam Gandhi, Software Developer http://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/3 void doSomething() { vector<Widget*> vwp; … // as before for (vector<Widget*>::iterator i = vwp.begin(); i != vwp.end(), ++i) { delete *i; } still there can be leak because of exception Uttam Gandhi, Software Developer http://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/3 void 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 above Uttam Gandhi, Software Developer http://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 time Uttam Gandhi, Software Developer http://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 erase AssocContainer<int> c; ...... for (AssocContainer<int>::iterator i = c.begin(); i!= c.end(); ++i) { if (badValue(*i)) c.erase(i); } Uttam Gandhi, Software Developer http://www.linkedin.com/pub/uttam-gandhi/21/7aa/24 Content last revised on 1/4/13
  • 20. Choosing Erasing Options AssocContainer<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 invalidating Uttam Gandhi, Software Developer http://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.htm Uttam Gandhi, Software Developer http://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 reserve Uttam Gandhi, Software Developer http://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 you're 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 Developer http://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 Developer http://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 destroyed Uttam Gandhi, Software Developer http://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 Developer http://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 Developer http://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 case Uttam Gandhi, Software Developer http://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 Developer http://www.linkedin.com/pub/uttam-gandhi/21/7aa/24 Content last revised on 1/4/13
  • 30. Functor for string dereference struct StringPtrLess: public binary_function<const string*, 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 Developer http://www.linkedin.com/pub/uttam-gandhi/21/7aa/24 Content last revised on 1/4/13
  • 31. Templatized functor for de-reference struct DereferenceLess { template <typename PtrType> bool operator()(PtrType pT1, PtrType pT2) const value, because we expect them { return *pT1 < *pT2; } }; Uttam Gandhi, Software Developer http://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 equivalent Uttam Gandhi, Software Developer http://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, we'll get back a pair of iterators that define a range containing both copies ¡  equal_range identifies a range of equivalent values Uttam Gandhi, Software Developer http://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 corrupt Uttam Gandhi, Software Developer http://www.linkedin.com/pub/uttam-gandhi/21/7aa/24 Content last revised on 1/4/13
  • 35. In-place modification of set/multiset value2/2 Uttam Gandhi, Software Developer http://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, sort Uttam Gandhi, Software Developer http://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 these Uttam Gandhi, Software Developer http://www.linkedin.com/pub/uttam-gandhi/21/7aa/24 Content last revised on 1/4/13
  • 38. Sorted vector v/s associative container 3/3 Uttam Gandhi, Software Developer http://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 saved Uttam Gandhi, Software Developer http://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, destroyed Uttam Gandhi, Software Developer http://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); —  Conversions Uttam Gandhi, Software Developer http://www.linkedin.com/pub/uttam-gandhi/21/7aa/24 Content last revised on 1/4/13
  • 42. const_iterator to iterator 1/2 Uttam Gandhi, Software Developer http://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 Developer http://www.linkedin.com/pub/uttam-gandhi/21/7aa/24 Content last revised on 1/4/13
  • 44. Destination Range should be big enough 1/3 Uttam Gandhi, Software Developer http://www.linkedin.com/pub/uttam-gandhi/21/7aa/24 Content last revised on 1/4/13
  • 45. Destination Range should be big enough 2/3 Uttam Gandhi, Software Developer http://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 position Uttam Gandhi, Software Developer http://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 criterion Uttam Gandhi, Software Developer http://www.linkedin.com/pub/uttam-gandhi/21/7aa/24 Content last revised on 1/4/13
  • 48. Sorting Options 2/3 Uttam Gandhi, Software Developer http://www.linkedin.com/pub/uttam-gandhi/21/7aa/24 Content last revised on 1/4/13
  • 49. Sorting Options 3/3 Uttam Gandhi, Software Developer http://www.linkedin.com/pub/uttam-gandhi/21/7aa/24 Content last revised on 1/4/13
  • 50. Remove algorithm on container of pointers Uttam Gandhi, Software Developer http://www.linkedin.com/pub/uttam-gandhi/21/7aa/24 Content last revised on 1/4/13
  • 51. After remove is called Uttam Gandhi, Software Developer http://www.linkedin.com/pub/uttam-gandhi/21/7aa/24 Content last revised on 1/4/13
  • 52. After erase is called Uttam Gandhi, Software Developer http://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_copy Uttam Gandhi, Software Developer http://www.linkedin.com/pub/uttam-gandhi/21/7aa/24 Content last revised on 1/4/13
  • 54. Use same algo for sort and search Uttam Gandhi, Software Developer http://www.linkedin.com/pub/uttam-gandhi/21/7aa/24 Content last revised on 1/4/13
  • 55. Copy_if implemented Uttam Gandhi, Software Developer http://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 Developer http://www.linkedin.com/pub/uttam-gandhi/21/7aa/24 Content last revised on 1/4/13
  • 57.
  • 58. Make functors adaptable Uttam Gandhi, Software Developer http://www.linkedin.com/pub/uttam-gandhi/21/7aa/24 Content last revised on 1/4/13
  • 59. ptr_fun Uttam Gandhi, Software Developer http://www.linkedin.com/pub/uttam-gandhi/21/7aa/24 Content last revised on 1/4/13
  • 60. Adaptable Functors Uttam Gandhi, Software Developer http://www.linkedin.com/pub/uttam-gandhi/21/7aa/24 Content last revised on 1/4/13
  • 61. not1 and bind2nd Uttam Gandhi, Software Developer http://www.linkedin.com/pub/uttam-gandhi/21/7aa/24 Content last revised on 1/4/13
  • 62. ptr_fun, mem_fun and mem_fun_ref —  3 ways to call C++ function Uttam Gandhi, Software Developer http://www.linkedin.com/pub/uttam-gandhi/21/7aa/24 Content last revised on 1/4/13
  • 63. for_each usage Uttam Gandhi, Software Developer http://www.linkedin.com/pub/uttam-gandhi/21/7aa/24 Content last revised on 1/4/13
  • 64. for_each implementation —  for_each is written in a way, its only compatible with call#1 Uttam Gandhi, Software Developer http://www.linkedin.com/pub/uttam-gandhi/21/7aa/24 Content last revised on 1/4/13
  • 65. mem_fun example Uttam Gandhi, Software Developer http://www.linkedin.com/pub/uttam-gandhi/21/7aa/24 Content last revised on 1/4/13
  • 66. 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 Developer http://www.linkedin.com/pub/uttam-gandhi/21/7aa/24 Content last revised on 1/4/13
  • 67. 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++ programmer Uttam Gandhi, Software Developer http://www.linkedin.com/pub/uttam-gandhi/21/7aa/24 Content last revised on 1/4/13
  • 68. Prefer member function to algorithm 1/2 —  Why ¡  Member functions are faster ¡  They integrate better with container(especially associative) —  Example Uttam Gandhi, Software Developer http://www.linkedin.com/pub/uttam-gandhi/21/7aa/24 Content last revised on 1/4/13
  • 69. 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 directly Uttam Gandhi, Software Developer http://www.linkedin.com/pub/uttam-gandhi/21/7aa/24 Content last revised on 1/4/13
  • 70. Search options 1/2 —  Logarithmic complexity ¡  binary_search ¡  lower_bound ¡  upper_bound ¡  equal_range ¡  Uses equivalence —  Linear Search Complexity ¡  find ¡  count ¡  Use equality Uttam Gandhi, Software Developer http://www.linkedin.com/pub/uttam-gandhi/21/7aa/24 Content last revised on 1/4/13
  • 71. 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 inserted Uttam Gandhi, Software Developer http://www.linkedin.com/pub/uttam-gandhi/21/7aa/24 Content last revised on 1/4/13
  • 72. 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 inserted Uttam Gandhi, Software Developer http://www.linkedin.com/pub/uttam-gandhi/21/7aa/24 Content last revised on 1/4/13
  • 73. lower_bound v/s upper_bound Uttam Gandhi, Software Developer http://www.linkedin.com/pub/uttam-gandhi/21/7aa/24 Content last revised on 1/4/13
  • 74. Use functor over functions Uttam Gandhi, Software Developer http://www.linkedin.com/pub/uttam-gandhi/21/7aa/24 Content last revised on 1/4/13
  • 75. 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% faster Uttam Gandhi, Software Developer http://www.linkedin.com/pub/uttam-gandhi/21/7aa/24 Content last revised on 1/4/13
  • 76. 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 retained Uttam Gandhi, Software Developer http://www.linkedin.com/pub/uttam-gandhi/21/7aa/24 Content last revised on 1/4/13
  • 77. 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 Developer http://www.linkedin.com/pub/uttam-gandhi/21/7aa/24 Content last revised on 1/4/13