Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Address of the pointed element whatever the iterator type/pointer is passed

Tags:

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 ?

like image 738
Vincent Avatar asked Aug 29 '12 13:08

Vincent


People also ask

Which iterator function returns the current pointed element?

An iterator must have these methods: current() - Returns the element that the pointer is currently pointing to. It can be any data type.

Is an iterator a pointer?

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.

What is iterator pointing in C++?

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.

What does the end iterator point to?

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.


1 Answers

You can dereference pointer and then take address of object.

template<IteratorType> void myFunction(const IteratorType& myIterator)
{
    _ptr = &(*myIterator);
}
like image 71
ForEveR Avatar answered Oct 28 '22 20:10

ForEveR