For Efficiency, Favor Specialized Over Generic Member Algorithms

The algorithms in the standard C++ library are generic and, as such, can be inefficient (or unavailable) with certain containers.

For example, the std::swap algorithm is generic but lists define an optimized member function std::list<>::swap that is much more efficient:

     std::list list1;    std::list list2;    // ...    std::swap(list1, list2); /* Inefficient */    list1.swap(list2);       /* Optimized */

Another example would be std::sort. As it requires a random-access iterator it would not work on std::list<> containters at all. One would need to use std::list<>::sort instead:

     std::list list;    // ...    std::sort(list); /* Error! */    list.sort();     /* OK */
Share the Post:
Share on facebook
Share on twitter
Share on linkedin


Recent Articles: