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

Which C 11 Standard Library Container Should I Choose?

DDD
DDDOriginal
2024-12-15 01:18:13760browse

Which C  11 Standard Library Container Should I Choose?

Selecting a C 11 Standard Library Container: A Comprehensive Guide

Selecting an appropriate container in C 11 is crucial for efficient data management. Unlike the well-known "C Container choice" cheat sheet, a C 11 version is yet to be created.

However, creating such a chart can be simplified by adhering to two principles: prioritizing semantics and opting for the simplest solution when multiple options exist. Performance considerations should be addressed only when handling large datasets.

Associative vs. Simple Sequence

Containers are categorized into two primary types: associative and simple sequence.

Associative Containers

Use associative containers for:

  • Easy searching by a single key
  • Sorted elements (ordered associative containers)

Simple Sequence Containers

Use simple sequence containers when:

  • Element order is irrelevant
  • Memory stability (fixed memory locations) is needed

Step-by-Step Selection Process

For Associative Containers

  • Ordered?

    • Yes: Use std::map or std::set (based on key-value separation)
    • No: Use std::unordered_map or std::unordered_set
  • Duplicates?

    • Yes: Use std::multimap or std::multiset
    • No: Use std::map or std::set

For Simple Sequence Containers

  • Memory stable?

    • Yes: Use std::list
  • Dynamically sized?

    • Known size at compilation time?: Use std::array
    • Unknown size?: Continue
  • Double-ended?

    • Yes: Use std::deque
    • No: Use std::vector

Default Choice

In most cases, unless associative or specific requirements exist, std::vector is the preferred choice (as recommended by Sutter and Stroustrup).

The above is the detailed content of Which C 11 Standard Library Container Should I Choose?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
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