istream_iterator将文件中的值读取到集合中
istream_iterator read values from file into set
我很难将istream_iterator用于我需要的目的。我有一个文件,我想逐行读取到一个集合中。我必须使用迭代器,我想知道我的代码或方法是否有问题。
我们非常感谢您的帮助。以下是我正在编写的代码的简化版本:
main.cpp
#include <iostream>
#include <fstream>
#include <string>
#include <set>
using namespace std;
int main() {
ifstream file("fruits.txt");
set<string> M;
copy(istream_iterator<string>(file),
istream_iterator<string>(),
[](string & s){ M.insert(s); });
for( auto val : M ) {
cout << val << ", ";
}
return 0;
}
fruits.txt
banana
apple
pear
strawberry
blueberry
peach
pear
apple
错误:
main.cpp:16:26: Variable 'M' cannot be implicitly
captured in a lambda with no capture-default specified
/Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr
/include/c++/v1/algorithm:1750:49: Cannot increment value of type '(lambda at
/Users/cnapoli22/Downloads/TEST SHIT/TEST SHIT/main.cpp:16:10)'
copy
的最后一个参数需要是迭代器,而不是lambda:
#include <algorithm>
#include <fstream>
#include <iostream>
#include <iterator>
#include <set>
#include <string>
using namespace std;
int main()
{
ifstream file("fruits.txt");
set<string> M;
copy(istream_iterator<string>(file),
istream_iterator<string>(),
inserter(M, M.end()));
for (auto const& val : M)
{
cout << val << ", ";
}
}
相关文章:
- 理解boost::asio-async_read在无需读取内容时的行为
- 使用新行和不使用新行读取文件
- 处理多个异常集合的C++方法
- 读取文件并输入到矢量中
- 给定n个元素的m个集合.在C++中找到出现在最大集合数中的元素
- 用c++从输入文件中读取另一行
- 读取文件的最后一行并输入到链接列表时出错
- 在进程中对同一管道进行读取和写入时C++管道出现问题
- 无法找到/读取配置文件.conf-FileIOException
- 如何使用Luacneneneba API正确读取字符串和表参数
- 如何将ampl中的集合表示为c++中的向量
- C++将文本文件中的数据读取到结构数组中
- 正在将csv文件读取为双精度矢量
- 为什么 sscanf 无法从一个字符串中读取uint64_t和字符?
- 检查值是否在集合p1和p2中,但不在p3中
- 带过滤器的现代迭代c++集合
- 为什么在读取文件大小时文件IO速度会发生变化
- 将集合插入/读取到地图中
- istream_iterator将文件中的值读取到集合中
- 从自定义集合(struct Array)中读取数据