In order to use the standard algorithm copy_n with an input iterator, you need to be sure that the input iterator can be dereferenced for N consecutive steps. How can you guarantee that if you cannot scan the values twice?
In order to use the standard algorithm copy_n with an input iterator, you need to be sure that the input iterator can be dereferenced for N consecutive steps. How can you guarantee that if you cannot scan the values twice?
It depends on what the iterator points to. There is no problem rescanning arrays, vectors, or many other containers.
Based on your previous posts, you are thinking of a stream. Perhaps copy_n is not the correct tool to use for streams.
Arrays and vectors give me random access iterators. However, the documentation says that an input iterator will be enough. My question is, how can it be?
To put it simply, if it fails to dereference then that is a bug in your application and the C++ runtime should terminate.
The parameters for std::copy_n are:
template< class InputIt, class Size, class OutputIt >
OutputIt copy_n( InputIt first, Size count, OutputIt result );
The second parameter is the amount of elements to copy. So basically, if you are just passing in any random value without checking the current size of the container then bad things will happen. Anything that you can get an iterator from should also have a length or size member which tells you how much it contains.
I believe anything that can provide guaranteed N items can also provide a forward iterator. Prove me wrong.
OK, I wrote a class that only has an input iterator. You are wrong.
You can never assume that the requirements for these functions will only ever work on STL classes. The generic nature of these algorithms means that they can work on anything that provides an iterator.
Could you show your class to me please?
I am trying to implement an iterator that compares equal to the end when it has read N values. The obvious approach (if my N is equal to your N) does not work because my iterator is at N, the underlying iterator has already read N + 1 values and that last value is lost.
2 people are following this question.