STL array in C++ (Standard Template Library)

 


The STL array is a part of the C++ Standard Template Library (STL) and is defined in the <array> header. It provides a fixed-size, type-safe, and optimized alternative to C-style arrays.


1️⃣ Syntax & Declaration

#include <iostream>
#include <array>  // Include STL array
using namespace std;

int main() {
    array<int, 5> arr = {10, 20, 30, 40, 50};  // Fixed-size array of 5 elements

    cout << "First Element: " << arr[0] << endl;
    cout << "Last Element: " << arr[4] << endl;

    return 0;
}

🔹 Output

First Element: 10
Last Element: 50

STL array has a fixed size and cannot be resized dynamically.


2️⃣ Accessing Elements

🔹 Using Indexing

cout << arr[2];  // Access 3rd element

🔹 Using .at(index) (Safe Access)

cout << arr.at(2);  // Access 3rd element safely

💡 .at() checks bounds and throws an exception if out of range.


3️⃣ Traversing an STL array

🔹 Using a Simple Loop

for (int i = 0; i < arr.size(); i++) {
    cout << arr[i] << " ";
}

🔹 Using a Range-Based Loop

for (int val : arr) {
    cout << val << " ";
}

🔹 Using Iterators

for (auto it = arr.begin(); it != arr.end(); it++) {
    cout << *it << " ";
}

✅ STL array supports iterators, making traversal easy.


4️⃣ Common STL array Functions

🔹 Size of the Array

cout << "Size: " << arr.size() << endl;

🔹 Check if Empty

if (arr.empty()) cout << "Array is empty";

🔹 First & Last Elements

cout << "First: " << arr.front() << endl;
cout << "Last: " << arr.back() << endl;

🔹 Fill the Array with a Value

arr.fill(100);  // All elements become 100

5️⃣ Sorting an STL array

#include <iostream>
#include <array>
#include <algorithm>  // Sorting functions
using namespace std;

int main() {
    array<int, 5> arr = {50, 10, 40, 20, 30};

    sort(arr.begin(), arr.end());  // Sort in ascending order

    cout << "Sorted Array: ";
    for (int val : arr) cout << val << " ";

    return 0;
}

🔹 Output

Sorted Array: 10 20 30 40 50

sort() uses iterators for efficient sorting.


6️⃣ Swapping Two STL Arrays

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

int main() {
    array<int, 3> arr1 = {1, 2, 3};
    array<int, 3> arr2 = {7, 8, 9};

    arr1.swap(arr2);  // Swap contents

    cout << "After swapping: \n";
    for (int val : arr1) cout << val << " ";  // 7 8 9
    cout << endl;
    for (int val : arr2) cout << val << " ";  // 1 2 3

    return 0;
}

swap() efficiently exchanges contents of two STL arrays.


7️⃣ Summary

std::array<T, N> → Fixed-size container for N elements.
Supports indexing, .at(), .front(), .back().
Works with iterators (begin(), end()).
Sorting using sort(arr.begin(), arr.end()).
Supports fill(), swap(), and empty().

Would you like an STL vector next? 🚀

Post a Comment

0 Comments