As of C++20, I would make use of a range from the Ranges library, because it offers a variety of range adaptors for creating different views on you vector. For your use case, I would use the range adaptor std::views::drop
as follows:
int main() {
std::vector<int> arr {1, 2, 3, 4, 5};
// Ignore the first two elements and pass only {3, 4, 5} to func().
func(arr | std::views::drop(2));
return 0;
}
This way you don't have to bother with interators or pointer/iterator arithmetic.
Also, no temporary vector is created for your shortened arr
, because the view adaptor drop()
creates a range that doesn't contain elements. The resulting range is just a view over the original vector arr
, but with a customized iteration behavior.
For the declaration of func()
I would use the placeholder type auto
for the function parameter, because the type of the resulting range is quite complex. This makes func()
a function template, though:
void func(auto range) {
for (int i : range)
std::cout << i << std::endl;
}
(Alternatively, you could pass arr
by reference to func()
and apply the range adaptor inside func()
.)
Output:
3
4
5
Code on Wandbox