
Hello,
I don't know why the following code does not work as expected. I hope the guru's here could lend me a hand.
For a test data file: 3 1 2 3 4 5 6
2 1.2 4.3 234.2 3.5656 67.88 345.3 <eof>
and 2 simple test helper class:
struct a { int i, j; }; std::istream& operator>>(std::istream& in, a & p) { in >> p.i >> p.j; return in; } std::ostream& operator<<(std::ostream& out, const a & p) { out << p.i << " " << p.j; return out; }
struct b { float i, j, k; }; std::istream& operator>>(std::istream& in, b & p) { in >> p.i >> p.j >> p.k; return in; } std::ostream& operator<<(std::ostream& out, const b & p) { out << p.i << " " << p.j << " " << p.k; return out; } [Snip]
copy_n is defined as:
template
OutputIterator copy_n( InputIterator first, InputIterator last, Size n, OutputIterator result) { // copies the first `n' items from `first' to `result'. Returns // the value of `result' after inserting the `n' items. // it ends before n iterations, if the last iterator is reached while( n-- && first != last) { *result = *first; ++first; ++result; } return result; } Change your copy_n() as follows:
template
OutputIterator copy_n( InputIterator first, InputIterator last, Size n, OutputIterator result) { // copies the first `n' items from `first' to `result'. Returns // the value of `result' after inserting the `n' items. // it ends before n iterations, if the last iterator is reached while( n-- && first != last) { *result = *first; if (n) ++first; ++result; } return result; } Regards, Dmitry
Hello Dmitry,
I really appreciate your help on such a naive question!
I'm prepared to getting no response from the list, for my
message is really a little bit lengthy, and somewhat off
the main stream of the list, I'm afraid. :-)
With your code change, the test code runs as expected,
so does my real program. But I just don't know why.
In fact, the copy_n function is a safe version of another
one:
template