Home > Backend Development > C++ > Which C 11 Standard Library Container Should I Use?

Which C 11 Standard Library Container Should I Use?

Susan Sarandon
Release: 2024-12-06 05:50:15
Original
328 people have browsed it

Which C  11 Standard Library Container Should I Use?

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!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template