0Pricing
C++ Academy · Lesson

Creating Views

Build views over strings.

From a String Literal

The simplest view comes from a string literal. The length is computed automatically.

#include <iostream>
#include <string_view>
int main() {
    std::string_view sv = "automatic length";
    std::cout << sv.size() << "\n";
}

From a std::string

A std::string converts to a view implicitly, letting you observe its contents without copying.

#include <iostream>
#include <string>
#include <string_view>
int main() {
    std::string s = "owned text";
    std::string_view sv = s;
    std::cout << sv << "\n";
}

All lessons in this course

  1. Why string_view
  2. Creating Views
  3. Pitfalls and Lifetimes
  4. String Algorithms
← Back to C++ Academy