如何使用istream_iterator將文字檔轉到vector? (C/C++) (STL)
stream_iterator除了能使用cin外,只要是stream都可用,如fstream,stringstream都可用。本範例demo如何利用stream_iterator將文字檔的每個單字轉到vector內。
1/*
2(C) OOMusou 2006 http://oomusou.cnblogs.com
3
4Filename : StreamIteratorInFileOutFile.cpp
5Compiler : Visual C++ 8.0 / ISO C++
6Description : Demo how to use istream_iterator from file to vector
7 and ostream_iterator from vector to file
8Release : 12/07/2006
9*/
10
11#include <fstream>
12#include <iostream>
13#include <vector>
14#include <algorithm>
15#include <string>
16#include <iterator>
17
18using namespace std;
19
20int main() {
21 ifstream inFile("books-11-30-2006.txt");
22 vector<string> svec;
23
24 // Copy cin to vector
25 copy(istream_iterator<string>(inFile), istream_iterator<string>(), back_inserter(svec));
26
27 // Sort vector
28 sort(svec.begin(), svec.end());
29
30 // Copy vector to cout
31 ofstream outFile("books-11-30-2006_r.txt");
32 copy(svec.begin(), svec.end(), ostream_iterator<string>(outFile,"\n"));
33
34 inFile.close();
35 outFile.close();
36}
2(C) OOMusou 2006 http://oomusou.cnblogs.com
3
4Filename : StreamIteratorInFileOutFile.cpp
5Compiler : Visual C++ 8.0 / ISO C++
6Description : Demo how to use istream_iterator from file to vector
7 and ostream_iterator from vector to file
8Release : 12/07/2006
9*/
10
11#include <fstream>
12#include <iostream>
13#include <vector>
14#include <algorithm>
15#include <string>
16#include <iterator>
17
18using namespace std;
19
20int main() {
21 ifstream inFile("books-11-30-2006.txt");
22 vector<string> svec;
23
24 // Copy cin to vector
25 copy(istream_iterator<string>(inFile), istream_iterator<string>(), back_inserter(svec));
26
27 // Sort vector
28 sort(svec.begin(), svec.end());
29
30 // Copy vector to cout
31 ofstream outFile("books-11-30-2006_r.txt");
32 copy(svec.begin(), svec.end(), ostream_iterator<string>(outFile,"\n"));
33
34 inFile.close();
35 outFile.close();
36}
使用這種寫法,優點是程式碼非常精簡,但缺點是一定得用一個Container接,如vector,實務上可能邊讀文字檔邊處理就好。
Keyword
stream_iterator, copy, vector, text