views::transform
C++23Apply a function to each element lazily.
Section hub
std::ranges::view_interface is a helper class template for defining a view interface.
template< class D >
requires std::is_class_v<D> && std::same_as<D, std::remove_cv_t<D>>
class view_interface;
(since C++20)
#include <iostream>
#include <ranges>
#include <vector>
template<class T, class A>
class VectorView : public std::ranges::view_interface<VectorView<T, A>>
{
public:
VectorView() = default;
VectorView(const std::vector<T, A>& vec) :
m_begin(vec.cbegin()), m_end(vec.cend())
{}
auto begin() const { return m_begin; }
auto end() const { return m_end; }
private:
typename std::vector<T, A>::const_iterator m_begin{}, m_end{};
};
int main()
{
std::vector<int> v = {1, 4, 9, 16};
VectorView view_over_v{v};
// We can iterate with begin() and end().
for (int n : view_over_v)
std::cout << n << ' ';
std::cout << '\n';
// We get operator[] for free when inheriting from view_interface
// since we satisfy the random_access_range concept.
for (std::ptrdiff_t i = 0; i != view_over_v.size(); ++i)
std::cout << "v[" << i << "] = " << view_over_v[i] << '\n';
}
| DR | Applied to | Behavior as published | Correct behavior |
|---|---|---|---|
| LWG 3549 | C++20 | view_interface was required to be derived from view_base,which sometimes required multiple view_base subobjects in a view | inheritance removed |
This hub groups the ranges library by user task rather than by raw reference tree shape. View types and adaptor objects are presented as the same conceptual item.
Start here for the adapters most people reach for first when building pipelines.
Apply a function to each element lazily.
Keep only elements that satisfy a predicate.
Keep the first N elements from a source range.
Skip the first N elements and expose the rest.
Split a range into non-overlapping fixed-size subranges.
Flatten a range of ranges into a single lazy sequence.
These adapt shape, ownership, or projection rather than representing the “headline” pipeline steps.
Normalize a range into a view-compatible form.
Adapt iterator/sentinel pairs into a common-range shape.
Wrap an existing range by reference.
Store and expose a range with unique ownership.
Package iterator + sentinel as a view-like object.
Project tuple-like elements to their key component.
Project tuple-like elements to their value component.
Newer adapters, kept as a compact scan list with only standard badges.
A lighter-weight index of the full ranges surface, grouped by conceptual task instead of raw page-tree names.