如何使用istream_iterator将cin转到vector? (C/C++) (STL)
本范例使用istream_iterator及copy(),将cin转到vector,只需一行的程序,vector经过sort(),再使用ostream_iterator将vector转到cout,也只需一行程序就可完成。
1/*
2(C) OOMusou 2006 http://oomusou.cnblogs.com
3
4Filename : StreamIteratorCinCout.cpp
5Compiler : Visual C++ 8.0 / ISO C++
6Description : Demo how to use istream_iterator from cin to vector
7 and ostream_iterator from vector to cout
8Release : 12/07/2006
9*/
10
11#include <iostream>
12#include <vector>
13#include <algorithm>
14#include <string>
15#include <iterator>
16
17using namespace std;
18
19int main() {
20 vector<string> svec;
21
22 // Copy cin to vector
23 copy(istream_iterator<string>(cin), istream_iterator<string>(), back_inserter(svec));
24
25 // Sort vector
26 sort(svec.begin(), svec.end());
27
28 // Copy vector to cout
29 copy(svec.begin(), svec.end(), ostream_iterator<string>(cout,"\n"));
30}
2(C) OOMusou 2006 http://oomusou.cnblogs.com
3
4Filename : StreamIteratorCinCout.cpp
5Compiler : Visual C++ 8.0 / ISO C++
6Description : Demo how to use istream_iterator from cin to vector
7 and ostream_iterator from vector to cout
8Release : 12/07/2006
9*/
10
11#include <iostream>
12#include <vector>
13#include <algorithm>
14#include <string>
15#include <iterator>
16
17using namespace std;
18
19int main() {
20 vector<string> svec;
21
22 // Copy cin to vector
23 copy(istream_iterator<string>(cin), istream_iterator<string>(), back_inserter(svec));
24
25 // Sort vector
26 sort(svec.begin(), svec.end());
27
28 // Copy vector to cout
29 copy(svec.begin(), svec.end(), ostream_iterator<string>(cout,"\n"));
30}
23行的istream_iterator<string>(cin),意思是将cin转成stream_iterator<string>这个template class,且骨子是string。而istream_iterator<string>(),呼叫了其default constructor,自动产生eof。
23行的copy(),还使用到back_inserter,由于Generic Algorithm的前提是不能改变Container的size,所以不能呼叫Container的member function,但要做insert的动作势必改变Container的size且需要Container的member function,所以只好透过back_inserter来『借刀杀人』,由back_inserter来呼叫Container的member function。
29行的ostream_iterator<string>(cout,"\n"),将ostream_iterator转成cout,且用"\n"换行,为什么不用std::endl呢?因为ostream_iterator的signature规定要用const char*,所以不能塞string。