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







































