简体   繁体   中英

How can I use std::copy to read directly from a file stream to a container?

I ran across a cool STL example that uses istream_iterators to copy from std input (cin) to a vector.

vector<string> col1;
copy(istream_iterator<string>(cin), istream_iterator<string>(),
    back_inserter(col));

How would I do something similar to read from a file-stream directly into a container? Let's just say its a simple file with contents:

"The quick brown fox jumped over the lazy dogs."

I want each word to be a separate element in the vector after the copy line.

Replace cin with file stream object after opening the file successfully:

ifstream file("file.txt");

copy(istream_iterator<string>(file), istream_iterator<string>(),
                                                 back_inserter(col));

In fact, you can replace cin with any C++ standard input stream.

std::stringstream ss("The quick brown fox jumped over the lazy dogs.");

copy(istream_iterator<string>(ss), istream_iterator<string>(),
                                                 back_inserter(col));

Got the idea? col will contain words of the string which you passed to std::stringstream .

与fstream实例而不是cin完全相同。

I don't think the copy function is needed since the vector has a constructor with begin and end as iterators.

Thus, I think this is OK for you:

ifstream file("file.txt");
vector<string> col((istream_iterator<string>(file)), istream_iterator<string>());

The redundant () is to remove the Most_vexing_parse

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM