使用iostream Iterator

來源:互聯網
上載者:User

標籤:檔案名稱   實現   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

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.