標籤:檔案名稱 實現 ext insert 通過 nbsp err 綁定 表示
以前只知道IteratorIterator class。平時編程中用的最多的就是拿他遍曆某種容器。
今天遇到一種新的使用方式,記錄之。
比如有這樣一個任務,從標準輸入裝置讀取一串string元素,將它們存到vector內,並進行排列,最後再將這些字串寫回標準輸出裝置,一般代碼大都會是這樣的.(已經注釋掉的)
#include<iostream>#include<iterator>#include<algorithm>#include<vector>#include<string>using namespace std;int main(){ string word; /*vector<string>text; while (cin>>word){ text.push_back(word); } sort(text.begin(), text.end()); for (int ix = 0; ix < text.size(); ix++) cout << text[ix] << ‘ ‘;*/ istream_iterator<string> is(cin); //將is綁定至標準輸入裝置 istream_iterator<string> eof; //表示要讀取的最後一個元素的下一個位置,對標準輸入裝置而言,end-of-file即代表last,只要在定義istream_iterator時不為他指定istream對象,它便代表end-of-file。 vector<string> text; copy(is, eof, back_inserter(text)); //back_inserter是Iterator Inserter,所謂的insertionadapter,避免使用容器的賦值符,因為使用=必須事先決定一個容器的大小。 sort(text.begin(), text.end()); ostream_iterator<string> os(cout, " "); copy(text.begin(), text.end(), os); return 0;}
但是通過iostream iterator可以用上述(沒有注釋掉的)的方法進行實現。
如果要輸入到檔案中可以添加如下代碼
ifstream in_file("檔案名稱");ofstream out_file("檔案名稱");if (!in_file || !out_file){ cerr << "unable to open the necessary files.\n"; return -1}2017-04-21 21:55:35
使用iostream Iterator