Choosing the Optimal C 11 Standard Library Container
The classic "C Container Choice" cheat sheet provides guidance on selecting the appropriate container for specific usage scenarios. However, it lacks an updated version for C 11.
To compensate, here is a textual workflow to aid in container selection:
1. Semantics First
Associative Containers:
- Use Associative Containers if you require searching by a single key.
- Choose Ordered Containers to maintain sorted elements.
- For separate key-value pairs, utilize Map; for only keys, consider Set.
- Enable duplicates with "multi" prefixes.
Simple Sequence Containers:
- Select an appropriate container based on the following criteria:
2. Memory Stability
- Use Lists if elements must remain in memory during container modifications.
- Default to List; use Forward_List only for reduced memory footprint.
3. Dynamic Sizing
- Employ Arrays if size is known at compile-time and remains constant, and elements are default constructible or initialized using curly braces.
4. Double-Ended
- Choose Deque if you need to add or remove items from both ends.
- Opt for Vector otherwise.
Examples
Scenario: Retrieving person data based on unique IDs.
- We require find functionality (Associative Container).
- Order is irrelevant (Unordered).
- Keys (IDs) are separate from values (Map).
- No duplicates (no "multi").
Result: std::unordered_map.
Note: If no specific constraints apply, Vector is recommended as the default choice for simple sequence containers.
The above is the detailed content of Which C 11 Standard Library Container Should I Use?. For more information, please follow other related articles on the PHP Chinese website!