What would be the most generic syntax for the following function :
template<IteratorType> void myFunction(const IteratorType& myIterator)
{
_ptr = &myIterator[0];
}
It take an iterator myIterator (it can be a raw pointer) and the goal is to assign the address of the object pointed by myIterator
to a raw pointer _ptr
. Currently I use &myIterator[0]
but I realized that only random access iterators have the operator [].
So is there a syntax that will work with all type of standard iterators and pointers ?
An iterator must have these methods: current() - Returns the element that the pointer is currently pointing to. It can be any data type.
The most obvious form of an iterator is a pointer. A pointer can point to elements in an array and can iterate through them using the increment operator (++). But, all iterators do not have similar functionality as that of pointers.
An iterator is an object (like a pointer) that points to an element inside the container. We can use iterators to move through the contents of the container. They can be visualised as something similar to a pointer pointing to some location and we can access content at that particular location using them.
In something like an std::vector the ::end() iterator will point to one past the last element. You can't dereference this iterator but you can compare it to another iterator. If you compare another iterator to end() you know you've reached the end of the container.
You can dereference pointer and then take address of object.
template<IteratorType> void myFunction(const IteratorType& myIterator)
{
_ptr = &(*myIterator);
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With