摘要&我的理解:使用std :: copy_if寫號碼到文件,無法得到正確的結果
我的問題可以到「使用istream_iterator兩次用相同的ifstream的」,這是不是一個很好的被稱爲因爲在第一次遍歷之後,流已經到達(文件結束)。由於我們使用istream_iterator
遍歷整個流:
- 因爲
istream_iterator
是單通迭代器,所以我們不能去 回再次重新加載流。 - 由於流已經到達文件結尾,即使我們將新的迭代器綁定到它,迭代器仍然指向文件結束。
感謝那些回答我的問題的人!
====================
更新:
我只是做了一些樣品測試:
- 有兩個不同
ifstream
對象,結果是正確的。 - 與兩個不同的
istream_iterator
綁定到相同的ifstream
obejct,結果不正確;而不是文件中的任何東西,我在那裏得到了號碼2
。
就像@aschepler在下面的回答,istream_iterator
是一個單通迭代器,它在自增後會失效;但是一個全新的迭代器如何仍然不能工作?爲什麼我必須創建兩個不同的ifstream
對象才能使程序正常工作?
感謝您的回答!
===================原創問題======================== ==
我有一個關於C++ primer 5th(p.407)練習10.33的問題。我的問題發生在這個部分:
使用ostream_iterators,將奇數寫入第一個輸出文件,然後將偶數寫入第二個文件。
一些認定中的位置:
ifstream ifs(argv[1]);
istream_iterator<int> int_in(ifs);
istream_iterator<int> int_in_eof;
ofstream ofs_odd(argv[2]);
ofstream ofs_even(argv[3]);
ostream_iterator<int> int_out_odd(ofs_odd, " ");
ostream_iterator<int> int_out_even(ofs_even, " ");
事實上的std :: for_each的工作做得很好:
for_each(int_in, int_in_eof, [&int_out_odd, &int_out_even](const int i)
{ *(i & 0X1 ? int_out_odd : int_out_even)++ = i; });
正確的結果看起來是這樣的:
input file: 1 2 3 4 5 6 7 8 9
output_odd: 1 3 5 6 9
output_even: 2 4 6 8
然後我試圖使用copy_if來實現:
//copy odd number to odd file
copy_if(int_in, int_in_eof, int_out_odd, [](const int i)
{return i & 0X1; });
//copy even number to even file
copy_if(int_in, int_in_eof, int_out_even, [](const int i)
{return !(i & 0X1); });
結果看起來是這樣的:
input file: 1 2 3 4 5 6 7 8 9
output_odd: 1 3 5 6 9
output_even:
我裏面什麼都沒有,甚至文件。
我的問題是第一個copy_if改變了istream內的任何東西嗎?
在此先感謝您的幫助!
我認爲最好的做法是創建一個容器來容納這些值,然後做後續的遍歷,如'矢量 input_values(istream_iterator (IFS),istream_iterator ());'否則,你會需要重新打開整個文件。 –