Question

Section 1.3.2 here in CGAL documentation argues to use OutputIterator for returning the result of convex_hull_2() because container is empty at the time of call so we cannot pass result.begin().

In a sample non-CGAL program, I tried to simply pass the address of empty container as an output argument to a function(which adds some elements to the container) and I was able access the elements back in the caller.

So I would like to know whether passing address of a container is always equivalent to passing an OutputIterator to that container? If it is so, then are there any other specific reasons to introduce OutputIterators in CGAL functions?

Was it helpful?

Solution

The advantage of OutputIterator is that you can make templates that can take any type of standard container. Another advantage compared to passing an address or a reference is that caller may choose to use to use either std::front_inserter or std::back_inserter depending on what order they want and which is faster/possible for their chosen container. The caller may even extend the functionality of the function with the use of a custom iterator.

Here is how you pass an OutputIterator to an empty container:

template<class Iter>
void foo(Iter it) {}

std::list<int> bar;
foo(std::inserter(bar, bar.begin()));

It's okay to call begin() on an empty container as long as the returned iterator is not dereferenced.

The reason that begin cannot simply be passed is because begin is not an OutputIterator.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top