can I define istream_iterator behavior?

T

thomas

hi guys,
I got a question about istream_iterator.

---code---
istream_iterator<int> input(cin), end;
vector<int> vec;
copy(input, end, inserter(vec, vec.begin()));
---code---

the problem is that I don't want to copy all the data from input to
vector.
I want to copy only "n" int values from input. Can I do that with
istream_iterator?
 
J

Jerry Coffin

hi guys,
I got a question about istream_iterator.

---code---
istream_iterator<int> input(cin), end;
vector<int> vec;
copy(input, end, inserter(vec, vec.begin()));
---code---

the problem is that I don't want to copy all the data from input to
vector.
I want to copy only "n" int values from input. Can I do that with
istream_iterator?

The problem here isn't really with istream_iterator, but with copy -- or
more accurately with the fact that the standard library provides copy
but not copy_n (an odd omission, given that it does provide fill_n,
generate_n, etc.). Fortunately, it's a pretty easy algorithm to write:

// warning: untested code
template <class InputIterator, class OutputIterator>
OutputIterator copy_n(InputIterator i1, OutputIterator i2, size_t n) {
for (size_t i=0; i<n; ++i, ++i1, ++i2)
*i2 = *i1;
return i2;
}

Using the definitions you have above, you'd use this to copy 10 ints
something like this:

copy_n(input, inserter(vec, vec.begin()), 10);

Note that using inserter on a vector with begin() as the insertion point
is quite expensive. If you really want to insert at the beginning,
you'll be far better off with a deque instead. Under the circumstances
(starting with an empty vector and copying a known number of items) you
could resize the vector to the required size, and then use vec.rbegin()
as the target of the copy. Either of these will be O(N) where your
current code is O(N!).
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,769
Messages
2,569,580
Members
45,054
Latest member
TrimKetoBoost

Latest Threads

Top