C++ Beginner

cpp_015: STL Array in C++

codeaddict 2025. 3. 10. 20:41

Introduction

The Standard Template Library (STL) array, introduced in C++11, is a fixed-size container that offers a safer and more convenient alternative to traditional C-style arrays. Defined in the <array> header, std::array combines the performance of raw arrays with the benefits of STL containers, such as knowing its own size, bounds checking with certain methods, and compatibility with STL algorithms.

In this lesson, we’ll cover:

  • What std::array is and how it works.
  • The syntax for declaring and using std::array.
  • Examples of working with std::array, including passing it to functions.
  • Two practice problems for you to solve.

Explanation

The std::array is a container that encapsulates a fixed-size array. Unlike C-style arrays, which are raw pointers to memory and don’t carry size information, std::array is a proper object that provides useful member functions like .size(), .at(), and iterators. It’s also more type-safe and easier to pass to functions since it behaves like a regular object.

Key features:

  • Fixed size, specified at compile time.
  • Knows its own size (no need to pass it separately).
  • Supports STL features like iterators and bounds checking with .at().
  • Passed by value or reference to functions.

Let’s explore the syntax and examples to see how it works!

Syntax for STL Array

Declaration

#include <array>
std::array<T, N> name;
  • T: The data type of the elements (e.g., int, double, char).
  • N: The size of the array (must be a constant known at compile time).
  • name: The variable name of the array.

Common Member Functions

  • .size(): Returns the number of elements.
  • .at(index): Accesses an element with bounds checking (throws an exception if out of bounds).
  • [index]: Accesses an element without bounds checking (faster but unsafe if misused).
  • .front(): Returns the first element.
  • .back(): Returns the last element.

Example of Syntax

#include <iostream>
#include <array>
using namespace std;

int main() {
    // Declare an STL array of 5 integers
    array<int, 5> arr = {10, 20, 30, 40, 50};

    // Access elements
    cout << "First element: " << arr[0] << endl;         // 10
    cout << "Element at index 2: " << arr.at(2) << endl; // 30
    cout << "Size of array: " << arr.size() << endl;     // 5

    return 0;
}

Problems with Old-Style Arrays

Old-style arrays are basic. You write them like this:

int numbers[3] = {5, 10, 15};

But they have issues:

  • No size info: The array doesn’t “know” how many boxes it has. If you forget the size, you might try to use a box that doesn’t exist, causing errors (called “out of bounds”).
  • Raw pointers: When you pass this array to a function, C++ doesn’t send the whole row of boxes — it just sends a “pointer” (an address in memory) to the first box. This can confuse beginners and lead to mistakes.
  • No safety: If you accidentally ask for numbers[10] (way past the 3 boxes), the program might crash or act weird because there’s no check to stop you.

What Makes STL array Better?

The STL array fixes these problems. It’s like a smart row of boxes that:

  • Knows its size: You tell it how many boxes it has when you create it, and it remembers that number.
  • Fixed size: Once you set the number of boxes (e.g., 5), you can’t change it. This makes it predictable and safe.
  • Safer access: It has a way to check if you’re asking for a box that exists (called “bounds checking”).
  • Acts like an object: You can pass it to functions easily without worrying about pointers.

Simple Example 

Problem Statement

Write a program that declares an STL array of integers, passes it to a function, and calculates the sum of its elements.

Solution

#include <iostream>
#include <array>
using namespace std;

// Function to calculate the sum of elements in an STL array
int calculateSum(const array<int, 5>& arr) {  // Passed by const reference for efficiency
    int sum = 0;
    for (int i = 0; i < arr.size(); i++) {
        sum += arr[i];
    }
    return sum;
}

int main() {
    // Declare and initialize an STL array
    array<int, 5> numbers = {1, 2, 3, 4, 5};

    // Pass the array to the function
    int result = calculateSum(numbers);

    cout << "The sum of the array elements is: " << result << endl;

    return 0;
}

Output

The sum of the array elements is: 15

Practice Problems

Problem 1: Finding the Minimum Element

Task: Write a program that:

  • Creates an STL array of 6 doubles.
  • Passes it to a function that finds the smallest number.
  • Prints the result in main().

Hint: Loop through and compare each item to find the smallest.

#include <iostream>
#include <array>
using namespace std;

double findMin(const array<double, 6>& arr) {
    double min = arr[0];
    for (int i = 1; i < arr.size(); i++) {
        if (arr[i] < min) {
            min = arr[i];
        }
    }
    return min;
}

int main() {
    array<double, 6> numbers = {3.5, 1.2, 4.8, 0.9, 2.7, 5.1};
    double result = findMin(numbers);
    cout << "Smallest number: " << result << endl; // Prints 0.9
    return 0;
}

Problem 2: Reversing an STL Array

Task: Write a program that:

  • Creates an STL array of 4 characters (e.g., {‘A’, ‘B’, ‘C’, ‘D’}).
  • Passes it to a function that reverses it (e.g., to {‘D’, ‘C’, ‘B’, ‘A’}).
  • Prints the reversed array in main().

Hint: Swap items from the start and end, moving inward.

#include <iostream>
#include <array>
using namespace std;

void reverseArray(array<char, 4>& arr) {
    for (int i = 0; i < arr.size() / 2; i++) {
        char temp = arr[i];
        arr[i] = arr[arr.size() - 1 - i];
        arr[arr.size() - 1 - i] = temp;
    }
}

int main() {
    array<char, 4> letters = {'A', 'B', 'C', 'D'};
    reverseArray(letters);
    cout << "Reversed array: ";
    for (int i = 0; i < letters.size(); i++) {
        cout << letters[i] << " "; // Prints D C B A
    }
    cout << endl;
    return 0;
}

Here’s how it works step by step:

  1. Swapping Logic:
  • You start by swapping the element at index 0 with the element at the last index arr.size() - 1.
  • Then, you swap the element at index 1 with the second-to-last element at index arr.size() - 2, and so on.

2. Why only go up to half?:

  • When you swap the element at index i with the element at index arr.size() - 1 - i, you're already taking care of two positions: i and arr.size() - 1 - i.
  • After the first swap, the first and last elements are reversed. After the second swap, the second and second-to-last elements are reversed, and so on.
  • If you continued swapping beyond arr.size() / 2, you'd essentially start swapping elements that have already been swapped.

 

3. Example: If the array has 4 elements, say: arr = ['a', 'b', 'c', 'd']:

  • First iteration: Swap arr[0] and arr[3] → arr = ['d', 'b', 'c', 'a']
  • Second iteration: Swap arr[1] and arr[2] → arr = ['d', 'c', 'b', 'a']
  • Now the array is fully reversed, and there’s no need to swap further.

In this case, the loop only needs to run twice (i = 0 and i = 1), which is half the size of the array.