C++ Arrays, std::string, string_view & std::vector Masterclass

โšก Modern C++ (C++17 / C++20 / C++23) ๐ŸŸข Lesson 7 ๐Ÿ“‚ Phase 07: Arrays, Strings & Vectors ๐Ÿ“… 2026 Master Edition
๐Ÿ“Œ Covered in this in-depth guide: Fixed Arrays vs std::array ยท std::string API ยท std::string_view (C++17) ยท std::vector push_back/reserve ยท Range-for Traversal

Welcome to Phase 7 (Chapter 7): C++ Arrays, std::string, string_view & std::vector Masterclass! Dynamic sequence containers form the backbone of modern software. In this guide, you will master C-style arrays vs std::array, std::string API manipulation, zero-allocation std::string_view (C++17), and dynamic std::vector operations.

1Container Comparison Matrix
ContainerMemory AllocationSize Fixed or Dynamic?Bounds Checked (.at())?
C Array (int arr[5])Stack / ContiguousFixed at compile timeNo (Danger of out-of-bounds!)
std::array<T, N>Stack / ContiguousFixed at compile timeYes (via .at(i))
std::stringHeap (Small String Opt)Dynamic sizingYes (via .at(i))
std::string_viewNon-owning Pointer+LenFixed slice viewYes
std::vector<T>Heap / Dynamic RAMResizable Dynamic ArrayYes (via .at(i))
2std::vector & std::string_view Code Demonstration
C++ โ€” std::vector, std::string & string_viewโ–ถ Run Code in C++ Compiler
#include <iostream>
#include <vector>
#include <string>
#include <string_view>

void printView(std::string_view sv) {
    std::cout << "StringView: " << sv << " (length: " << sv.length() << ")\n";
}

int main() {
    // std::vector Operations
    std::vector<int> marks{85, 90, 78, 92};
    marks.push_back(88);
    marks.push_back(95);

    std::cout << "Vector size: " << marks.size() << ", capacity: " << marks.capacity() << "\n";
    std::cout << "Marks: ";
    for (int m : marks) {
        std::cout << m << " ";
    }
    std::cout << "\n";

    // std::string & std::string_view
    std::string text{"Modern C++ High-Performance Computing"};
    std::string_view slice{text.c_str() + 7, 3}; // Zero-allocation view of "C++"
    printView(slice);

    return 0;
}
3Technical FAQs

Q1: What is the difference between vector size() and capacity()?

size() is the number of elements currently stored. capacity() is the total memory allocated before requiring reallocation.

Q2: Why use vector.reserve(n)?

Calling reserve(n) pre-allocates memory for n elements, avoiding repeated memory reallocation and element copying during push_back().

Q3: Why is std::string_view faster than const std::string&?

std::string_view does NOT allocate memory or copy string data โ€” it simply wraps a pointer and length, enabling zero-allocation substrings.

Q4: What is Small String Optimization (SSO)?

Most C++ compilers store short strings (up to 15-23 characters) directly inside the std::string object on the stack without heap allocation.

Q5: Difference between [] indexing and .at() method?

arr[i] does zero bounds checking for speed. arr.at(i) throws std::out_of_range exception if index is invalid.