STL: Algorithms
Team LiB
Previous Section Next Section

STL: Algorithms

83. Use a checked STL implementation.

Safety first (see Item 6): Use a checked STL implementation, even if it's only available for one of your compiler platforms, and even if it's only used during pre-release testing.

84. Prefer algorithm calls to handwritten loops.

Use function objects judiciously: For very simple loops, handwritten loops can be the simplest and most efficient solution. But writing algorithm calls instead of handwritten loops can be more expressive and maintainable, less error-prone, and as efficient.

When calling algorithms, consider writing your own custom function object that encapsulates the logic you need. Avoid cobbling together parameter-binders and simple function objects (e.g., bind2nd, plus ), which usually degrade clarity. Consider trying the [Boost] Lambda library, which automates the task of writing function objects.

85. Use the right STL search algorithm.

Search "just enough"the right search may be STL (slower than light), but it'll still be pretty fast: This Item applies to searching for a particular value in a range, or for the location where it would be if it were in the range. To search an unsorted range, use find/find_if or count/count_if. To search a sorted range, use lower_bound, upper_bound, equal_range, or (rarely) binary_search. (Despite its common name, binary_search is usually not the right choice.)

86. Use the right STL sort algorithm.

Sort "just enough:" Understand what each of the sorting algorithms does, and use the cheapest algorithm that does what you need.

87. Make predicates pure functions.

Predicate purity: A predicate is a function object that returns a yes/no answer, typically as a bool value. A function is pure in the mathematical sense if its result depends only on its arguments (note that this use of "pure" has nothing to do with pure virtual functions).

Don't allow predicates to hold or access state that affects the result of their operator(), including both member and global state. Prefer to make operator() a const member function for predicates (see Item 15).

88. Prefer function objects over functions as algorithm and comparer arguments.

Objects plug in better than functions: Prefer passing function objects, not functions, to algorithms. Comparers for associative containers must be function objects. Function objects are adaptable and, counterintuitively, they typically produce faster code than functions.

89. Write function objects correctly.

Be cheap, be adaptable: Design function objects to be values that are cheap to copy. Where possible, make them adaptable by inheriting from unary_- or binary_function.

    Team LiB
    Previous Section Next Section