Reputation: 661
I am having difficulty using the istream_iterator for the purpose I need. I have a file that I want to read line by line into a set. I have to use the iterator and I was wondering if there's something wrong with my code or my approach.
The help is much appreciated. Here's a simplified version of the code I'm writing:
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
Errors:
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)'
Upvotes: 1
Views: 4506
Reputation: 14390
The last argument to copy
needs to be an iterator, not a 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 << ", ";
}
}
Upvotes: 4