开发者

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.


Exactly the same with the fstream instance instead of 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

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜