Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

std::string_view for STL containers

Tags:

c++

stl

Here is a great explanation of what a string_view object is.

Are there '_view' objects for any of the STL containers besides std::string?

Seems to me that it is an extremely useful thing to have. Imagine a std::vector_view class that simply stores a start iterator and a length field. Not actually owning the underlying data allows for awesome efficiency improvements.

like image 456
Adam Avatar asked Aug 08 '18 13:08

Adam


People also ask

What is std :: String_view for?

The std::string_view, from the C++17 standard, is a read-only non-owning reference to a char sequence. The motivation behind std::string_view is that it is quite common for functions to require a read-only reference to an std::string-like object where the exact type of the object does not matter.

Should I pass string_view by reference?

So, frequently, you can pass string_view by reference and get away with it. But you should pass string_view by value, so that the compiler doesn't have to do those heroics on your behalf. And so that your code-reviewer doesn't have to burn brain cells pondering your unidiomatic decision to pass by reference.

Is std::string an STL container?

It is part of STL indeed.

How are C++ STL containers implemented?

They are implemented as class templates, which allows great flexibility in the types supported as elements. The container manages the storage space for its elements and provides member functions to access them, either directly or through iterators (reference objects with similar properties to pointers).


1 Answers

There is a proposal for span, which is a view over a contiguous range of objects: http://wg21.link/p0122. See also: What is a “span” and when should I use one?.

The GSL library also provides gsl::span.


This might be stretching it, but I also proposed function_ref, which is basically a view over a Callable: http://wg21.link/p0792

like image 82
Vittorio Romeo Avatar answered Oct 26 '22 20:10

Vittorio Romeo