CKTIS / C++
std::views::drop — skipping the first N elements
std::views::drop creates a view of a range without its first N elements, without erasing them from the container. Use either the two-argument call or pipeline syntax. The number of elements to skip must be nonnegative.
Version: C++23; repository compiler flag, production runtime not attested
Syntax
#include <ranges>
std::views::drop(range, count)
range | std::views::drop(count)std::views::drop, available through <ranges>, is a range adaptor object. Writing std::views::drop(range, count) or range | std::views::drop(count) gives a view that skips elements from the beginning of the range. The number of positions to skip is determined by count after conversion to the range's iterator difference type. If the converted value is zero, the view includes all elements; if it is at least the length of a finite range, the result is empty.
The adaptor does not erase elements from the container or create a new container holding copies of the remaining values. The result is usually a std::ranges::drop_view, but the standard specifies another equivalent view for certain range types. Do not assume a particular result type; use auto.
count must be convertible to the range's iterator difference type. Both the supplied value and the converted value must be nonnegative. A negative value does not mean skipping from the end. If the view refers to an existing container, that container must remain alive while the view is used; operations that invalidate its iterators can also make using the view unsafe.
Skipping is not always constant-time: finding the beginning may require traversing the skipped elements. For a range satisfying forward_range, drop_view caches the computed beginning when needed to meet complexity requirements. In the example, values still contains five elements, while iterating over tail prints 30 40 50.
Examples
#include <array>
#include <iostream>
#include <ranges>
int main() {
std::array<int, 5> values{10, 20, 30, 40, 50};
auto tail = values | std::views::drop(2);
bool first = true;
for (int value : tail) {
if (!first) std::cout << ' ';
std::cout << value;
first = false;
}
std::cout << '\n';
}
Result
30 40 50
The displayed code and declared result were verified in an isolated environment using the method recorded in the verification evidence for this exact version.