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:
  1. #include <format>
  2. #include <iostream>
  3. #include <string_view>
  4.  
  5. void find_word(std::string_view text, std::string_view word) {
  6.  
  7.     size_t pos = text.find(word);
  8.     if (pos != std::string_view::npos)
  9.         std::cout << std::format("Word found at position: {}\n", pos);
  10.     else
  11.         std::cout << "Word not found\n";
  12. }
  13. int main() {
  14.  
  15.     std::string str = "The quick brown fox jumps over the lazy dog";
  16.     std::string_view sv = str;
  17.  
  18.     find_word(sv, "quick");
  19.     find_word(sv, "lazy");
  20.     find_word(sv, "hello");
  21.  
  22. }

Add a Comment

Comments are closed.

Comments (0)

There are currently no comments on this entry.