Spans, string_view, and Ranges - Four View types (C++17 to C++23) -- Bartlomiej Filipek

spans_string_view.pngIn this blog post, we’ll look at several different view/reference types introduced in Modern C++. The first one is string_view added in C++17. C++20 brought std::span and ranges views. The last addition is std::mdspan from C++23.

Spans, string_view, and Ranges - Four View types (C++17 to C++23)

by Bartlomiej Filipek

From the article:

The std::string_view type is a non-owning reference to a string. It provides an object-oriented way to represent strings and substrings without the overhead of copying or allocation that comes with std::stringstd::string_view is especially handy in scenarios where temporary views are necessary, significantly improving the performance and expressiveness of string-handling code. The view object doesn’t allow modification of characters in the original string.
Here's a basic example:
#include <format>
#include <iostream>
#include <string_view>

void find_word(std::string_view text, std::string_view word) {

    size_t pos = text.find(word);
    if (pos != std::string_view::npos)
        std::cout << std::format("Word found at position: {}\n", pos);
        std::cout << "Word not found\n";
int main() {

    std::string str = "The quick brown fox jumps over the lazy dog";
    std::string_view sv = str;

    find_word(sv, "quick");
    find_word(sv, "lazy");
    find_word(sv, "hello");


Add a Comment

Comments are closed.

Comments (0)

There are currently no comments on this entry.