SyntaxStudy
Sign Up
C++ Sequence Containers: vector, array, and deque
C++ Beginner 1 min read

Sequence Containers: vector, array, and deque

The Standard Template Library (STL) provides a rich set of generic containers, algorithms, and iterators. 'std::vector' is the most widely used container — a dynamically resizable array that stores elements contiguously in memory, offering O(1) random access and amortised O(1) push_back. Its memory layout is identical to a C array, making it interoperable with C APIs and cache-friendly for iteration. 'std::array' is a fixed-size array whose size is a compile-time constant encoded in the type. It has zero overhead compared with a raw C array but gains the full STL interface: iterators, 'size()', 'at()' with bounds checking, and compatibility with STL algorithms. Prefer 'std::array' over raw C arrays whenever the size is known at compile time. 'std::deque' (double-ended queue) provides O(1) push and pop at both ends while maintaining O(1) random access, at the cost of non-contiguous memory storage. It is the underlying container for 'std::queue' and 'std::stack' by default. When frequent insertion at the front is needed, 'deque' outperforms 'vector' significantly.
Example
#include <iostream>
#include <vector>
#include <array>
#include <deque>
#include <algorithm>
#include <numeric>   // std::iota

int main() {
    // --- std::vector ---
    std::vector<int> v;
    v.reserve(8);           // pre-allocate without changing size
    for (int i = 1; i <= 5; ++i) v.push_back(i * 10);

    std::cout << "vector: ";
    for (int x : v) std::cout << x << " ";
    std::cout << "\n";

    v.erase(v.begin() + 2); // erase element at index 2
    v.insert(v.begin(), 0); // insert 0 at front
    std::cout << "after erase+insert: ";
    for (int x : v) std::cout << x << " ";
    std::cout << "\n";

    // --- std::array ---
    std::array<int, 5> arr;
    std::iota(arr.begin(), arr.end(), 1);  // fill 1,2,3,4,5
    std::cout << "array sum: "
              << std::accumulate(arr.begin(), arr.end(), 0) << "\n";

    // --- std::deque ---
    std::deque<std::string> dq;
    dq.push_back("middle");
    dq.push_front("front");
    dq.push_back("back");

    std::cout << "deque: ";
    for (const auto& s : dq) std::cout << s << " ";
    std::cout << "\n";

    dq.pop_front();
    std::cout << "after pop_front: " << dq.front() << "\n";

    return 0;
}