I don't understand why I need to put another iterator as the second argument in the call to std::copy()
for reading through a file. How is iterator 'end' ending of a file?
vector<Point> v;
istream_iterator<Point> is(file), end;
copy(is, end, back_inserter(v));
std::copy. Copies the elements in the range [first,last) into the range beginning at result . The function returns an iterator to the end of the destination range (which points to the element following the last element copied).
The primary purpose of an iterator is to allow a user to process every element of a container while isolating the user from the internal structure of the container. This allows the container to store elements in any manner it wishes while allowing the user to treat it as if it were a simple sequence or list.
copy() function is a library function of algorithm header, it is used to copy the elements of a container, it copies the elements of a container from given range to another container from a given beginning position. Note:To use copy() function – include <algorithm> header or you can simple use <bits/stdc++.
An iterator is used to point to the memory address of the STL container classes. For better understanding, you can relate them with a pointer, to some extent. Iterators act as a bridge that connects algorithms to STL containers and allows the modifications of the data present inside the container.
How is iterator 'end' ending of a file?
By convention and/or a design decision in the standard library. The iterator end
is default-constructed, and on cppreference, we learn about the default std:istream_iterator
constructor:
constexpr istream_iterator();
Constructs the end-of-stream iterator, value-initializes the stored value [...]
The deeper reasoning is that the standard algorithms are built around the concept of a half-open range, often denoted as [first, last)
. The is
iterator must be distinguished from some kind of end sentinel last
- otherwise, std::copy
can't know when reading from the input is not meaningful anymore (i.e., when it has reached the end of the file). In your case, this is end
.
Why?
You need to tell the algorithm somehow how many elements it should copy. Note that copy
is generic and the reason to use iterators is to be agnostic of the actual container. Hence, the algorithm has no way to stop when it reaches the end of the container. All it has is the two iterators you pass it.
How?
This is just how it is defined in the language. If you look at the constructor that takes no arguments you see that it creates a special end-of-stream iterator. From cppreference:
constexpr istream_iterator(); (1)
1) Constructs the end-of-stream iterator, value-initializes the stored value. This constructor is constexpr if the initializer in the definition auto x = T(); is a constant initializer.
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