[Zz] How to Use istream_iterator to convert CIN to vector? (C/C ++) (STL)

Source: Internet
Author: User

In this example, we use istream_iterator and copy () to convert CIN to a vector. We only need a line of program, and the vector passes through sort (). Then we use ostream_iterator to convert the vector to cout, you only need one line of program.

1 /*
(2) oomusou 2006 Http://oomusou.cnblogs.com
3
4 filename: streamiteratorcincout. cpp
5 Compiler: Visual C ++ 8.0/iso c ++
6 Description: Demo how to use istream_iterator From CIN to Vector
7 and ostream_iterator from vector to cout
8 release: 12/07/2006
9 */
10
11 # include <iostream>
12 # include <vector>
13 # include <algorithm>
14 # include <string>
15 # include <iterator>
16
17 using 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}


Istream_iterator <string> (CIN) on the 23th line, which means converting CIN into stream_iterator <string> This template class, and the bone is string. Istream_iterator <string> () calls its default constructor to automatically generate an EOF.

The 23-line copy () operation also uses back_inserter. Because the premise of generic algorithm is that the container size cannot be changed, the member function of the container cannot be called, however, the insert action is bound to change the size of the container and the member function of the container is required. Therefore, we have to use back_inserter to call the member function of the container.

The 29-row ostream_iterator <string> (cout, "\ n") converts ostream_iterator into a cout and uses "\ n" for line feed. Why not use STD: Endl? Because the signature of ostream_iterator requires the use of const char *, the string cannot be entered.

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

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.