Chapter 10. Optimize Data Structures
A thing of beauty is a joy forever
John Keats (1818)
If you have never stopped to marvel at the container classes of the C++ standard library (formerly the Standard Template Library, or STL), perhaps you should do so now. At the time it was introduced into the draft C++ standard in 1994, Stepanov’s Standard Template Library was the first reusable library of efficient containers and algorithms. Prior to the STL, every project developed its own linked list and binary tree implementations, possibly adapting source code from other users. C has no equivalent. Standard library containers have allowed many programmers to forget their algorithms and data structures classes and choose exclusively from the standard library’s menu of prebuilt containers for the past 20 years.
Get to Know the Standard Library Containers
There are many things to like about the C++ standard library containers, such as uniform naming and a consistent notion of iterators for traversing the containers. But for optimization purposes, some properties are especially important. These include:
Big-O performance guarantees for the cost of insertion and deletion
Amortized constant-time cost of appending to sequence containers
Ability to finely control the dynamic memory allocated by the container
The C++ standard library containers seem almost similar enough that they can be substituted for one another, notwithstanding their obviously different implementations. But this ...