liveBook · Manning

Array

As explained in Learn C++ by Example

An array is a fixed-size sequence of elements stored in contiguous positions and accessed by index.

An array stores a known number of elements in a fixed-size sequence. In C++, std::array records both the element type and compile-time size, making it useful when a collection will not grow. section 5.1.5

Use an array when:

  • The number of elements is known in advance, such as the 52 cards in a full deck. section 5.0 section 5.1.5
  • You want vector-like indexed access through operator[], while retaining a fixed size and small housekeeping overhead. section 5.1.5
  • You need the underlying contiguous data through data(), including for a function expecting a pointer. section 5.1.5

A deck of cards

Declare a deck with std::array<Card, 52> deck. Build it by iterating through four suits and thirteen values, assigning each Card and advancing an iterator. Unlike a vector, the deck does not grow with push_back or emplace. section 5.1.5

Listing 5.17 Building a deck of cards
std::array<Card, 52> create_deck()
{
    std::array<Card, 52> deck;
    auto card = deck.begin();                                         #1
    for (auto suit : 
        {Suit::Hearts, Suit::Diamonds, Suit::Clubs, Suit::Spades})    #2
    {    
        for (int value = 1; value <= 13; value++)                     #3
        {
            *card = Card{ FaceValue(value), suit };                   #4
            ++card;                                                   #5
        }
    }
    return deck;
}

Follow the complete deck-building function, including suit iteration, card assignment, and iterator advancement. section 5.1.5

How Learn C++ by Example covers it

How deep it goes
Explains compile-time sizing, storage differences, initialization, indexing, iterators, and data access without detailing array internals.
Examples
Builds a 52-card deck by combining four suits with thirteen face values.
What it assumes
Assumes basic C++ collections and introduces fixed-size arrays by comparing them with vectors.
What you can do after
Apply it via std::array to declare, initialize, traverse, index, and expose fixed-size collections.
How it connects
Contrasts std::vector and C-style arrays, and connects arrays with initializer lists, iterators, operator[], and data().

Also explained in

Compare how 40 books explain array →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Learn C++ by Example. The section links point to the parts of the book it draws on.