Skip to content
Justice Tech School

string_view and Iterators

string_view is a cheap read only view of text without copying. Iterators generalise pointers to all containers, and begin, end, advance and distance work with them.

Example
#include <string_view>
string_view sv = "hello world";
cout << sv.substr(0, 5) << " " << sv.size() << "\n";
vector<int> v = {10, 20, 30, 40};
auto it = v.begin();
advance(it, 2);
cout << *it << " " << distance(v.begin(), it) << "\n";
for (auto r = v.rbegin(); r != v.rend(); ++r) cout << *r << " ";
cout << "\n";

Result

hello 11
30 2
40 30 20 10 

Exercise

Read only text view.

std:: sv = "x";

Quiz Test

What does string_view avoid?

These free lessons are for learning. Join a full course for projects, mentor feedback and a verified certificate.