Skip to main content

Lesson 5 of 7

string_view, span & std::ranges (C++20 Intro)

`std::string_view` (C++17) is a **non-owning view** into string data - cheap to construct and pass, eliminates string copies in read-only paths. `std::span<T>` (C++20) is its equivalent for contiguous arrays. `std::ranges` (C++20) provides **range adaptors** - lazy, composable transformations using the `|` pipe operator, making complex queries readable and efficient.

12 minBy Priygop Editorial TeamUpdated 2026Peer Reviewed & Verified

string_view, span & std::ranges Pipeline

string_view, span & std::ranges Pipeline
#include <iostream>
#include <string>
#include <string_view>
#include <vector>
#include <span>         // C++20
#include <algorithm>
#include <ranges>       // C++20
#include <numeric>

// ── string_view - zero-cost string parameter ──────────────────
// WRONG: void process(const std::string& s) - forces heap alloc for literals
// RIGHT: void process(std::string_view sv)   - works for literals, string, char*
void count_vowels_view(std::string_view sv) {
    auto count = std::count_if(sv.begin(), sv.end(), [](char c) {
        return std::string_view{"aeiouAEIOU"}.find(c) != std::string_view::npos;
    });
    std::cout << "Vowels in "" << sv << "": " << count << "
";
}

// ── span - non-owning view of contiguous data ────────────────
void sum_span(std::span<const int> data) {  // works with array, vector, etc.
    int total = std::accumulate(data.begin(), data.end(), 0);
    std::cout << "sum=" << total << "
";
}

int main() {
    // string_view from different sources - no allocation!
    count_vowels_view("Hello World");         // const char*
    std::string s = "Hello World";
    count_vowels_view(s);                     // std::string
    count_vowels_view(s.substr(0, 5));        // sub-view (substr allocates though)
    count_vowels_view(std::string_view(s).substr(0, 5)); // truly zero-copy

    // string_view useful methods
    std::string_view sv = "   hello world   ";
    sv.remove_prefix(sv.find_first_not_of(' '));  // trim leading spaces
    std::cout << sv << "
";  // "hello world   "

    // span
    int arr[] = {1, 2, 3, 4, 5};
    sum_span(arr);                         // C-array → span

    std::vector<int> vec{6, 7, 8, 9, 10};
    sum_span(vec);                         // vector → span

    sum_span(std::span<int>(vec).subspan(1, 3)); // span of vec[1..3]

    // ── std::ranges - C++20 pipeline (concept intro) ─────────
    #ifdef __cpp_lib_ranges   // check availability
    std::vector<int> nums{1, 2, 3, 4, 5, 6, 7, 8, 9, 10};

    // Composing range views (lazy - evaluated on demand)
    auto even_squares =
        nums
        | std::views::filter([](int n){ return n % 2 == 0; })  // keep evens
        | std::views::transform([](int n){ return n * n; });    // square them

    for (int v : even_squares) std::cout << v << " ";  // 4 16 36 64 100
    std::cout << "
";

    // ranges::sort - cleaner than std::sort + begin/end
    std::vector<int> tosort{5, 3, 8, 1, 9};
    std::ranges::sort(tosort);  // no need for .begin()/.end()!
    for (int v : tosort) std::cout << v << " ";
    std::cout << "
";  // 1 3 5 8 9

    // std::views::take, drop
    auto first5 = nums | std::views::take(5);
    auto skip3  = nums | std::views::drop(3);
    // Composing:
    auto middle = nums | std::views::drop(2) | std::views::take(5);
    for (int v : middle) std::cout << v << " ";  // 3 4 5 6 7
    std::cout << "
";
    #else
    std::cout << "std::ranges requires C++20 (compile with -std=c++20)
";
    #endif

    return 0;
}

Common Mistakes

  • `string_view` dangling - `string_view sv = std::string("temp").substr(0, 3)` - the temporary `std::string` is destroyed at the end of the full-expression, leaving `sv` dangling. Never store `string_view` of a temporary that goes out of scope before the view is used.
  • `span` of a `vector` after `push_back` - `span` stores a raw pointer to the vector's data. If `push_back` reallocates the vector, the span's pointer is dangling. Only use span when the container's lifetime and size are stable.
  • std::ranges views are lazy - `auto r = nums | filter(...) | transform(...)` does no work until you iterate. This is efficient, but if you store the view and then modify `nums`, the view sees the modified elements (or crashes if iterator is invalidated).

Tip

Tip

Practice stringview span stdranges C20 Intro in small, isolated examples before integrating into larger projects. Breaking concepts into small experiments builds genuine understanding faster than reading alone.

Diagram
Loading diagram…

Composable lazy evaluation pipelines with zero allocation overhead

Practice Task

Note

Practice Task - (1) Write a working example of stringview span stdranges C20 Intro from scratch without looking at notes. (2) Modify it to handle an edge case (empty input, null value, or error state). (3) Share your solution in the Priygop community for feedback.

Quick Quiz

Common Mistake

Warning

A common mistake with stringview span stdranges C20 Intro is skipping edge case testing - empty inputs, null values, and unexpected data types. Always validate boundary conditions to write robust, production-ready cpp code.

Key Takeaways

  • `std::string_view` (C++17) is a **non-owning view** into string data - cheap to construct and pass, eliminates string copies in read-only paths.
  • `string_view` dangling - `string_view sv = std::string("temp").substr(0, 3)` - the temporary `std::string` is destroyed at the end of the full-expression, leaving `sv` dangling. Never store `string_view` of a temporary that goes out of scope before the view is used.
  • `span` of a `vector` after `push_back` - `span` stores a raw pointer to the vector's data. If `push_back` reallocates the vector, the span's pointer is dangling. Only use span when the container's lifetime and size are stable.
  • std::ranges views are lazy - `auto r = nums | filter(...) | transform(...)` does no work until you iterate. This is efficient, but if you store the view and then modify `nums`, the view sees the modified elements (or crashes if iterator is invalidated).

Topics in This Module

0/7 done