The std::end
function returns an iterator pointing to the past-the-end element of the container passed as an argument. However, for std::unique_ptr<T[]>
, which is a smart pointer managing a dynamic array of objects of type T
, the std::end
function cannot be used directly because std::unique_ptr<T[]>
is not a container.
To obtain an iterator to the past-the-end element of the managed array, you can use the std::unique_ptr<T[]>::get()
function to obtain a raw pointer to the managed array, and then use pointer arithmetic to obtain a pointer to the past-the-end element.
Here is an example of how to use std::end
with std::unique_ptr<T[]>
:
#include <iostream>
#include <memory>int main() {
std::unique_ptr<int[]> arr(new int[5]{1, 2, 3, 4, 5});// Get a raw pointer to the managed array
int* ptr = arr.get();// Use pointer arithmetic to obtain a pointer to the past-the-end element
int* endPtr = ptr + 5;// Use std::end with the pointer to the past-the-end element
auto endIter = std::make_move_iterator(endPtr);
auto beginIter = std::make_move_iterator(ptr);for (auto it = beginIter; it != endIter; ++it) {
std::cout << *it << ‘ ‘;
}return 0;
}
In the example above, std::make_move_iterator
is used to create move iterators from the raw pointers obtained from std::unique_ptr<T[]>::get()
. This is necessary because std::unique_ptr<T[]>
manages the lifetime of the array, and we cannot create regular iterators from raw pointers.