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 << ", ";
}
}
我无法将 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 << ", ";
}
}