[英]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. 我遇到了一个很酷的STL示例,该示例使用istream_iterators从std输入(cin)复制到向量。
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: 成功打开文件后,将
cin
替换为文件流对象:
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. 实际上,您可以用任何C ++标准输入流替换
cin
。
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
. col
将包含您传递给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. 我认为不需要复制功能,因为矢量具有一个以begin和end作为迭代器的构造函数。
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 多余的()是删除Most_vexing_parse
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.