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

a 夏天 提交于 2019-12-30 09:56:46

问题


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.


回答1:


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.




回答2:


Exactly the same with the fstream instance instead of cin.




回答3:


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



来源:https://stackoverflow.com/questions/7152427/how-can-i-use-stdcopy-to-read-directly-from-a-file-stream-to-a-container

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!