2015-11-24 35 views
1

我有困难使用istream_iterator为我需要的目的。我有一个文件,我想逐行读入一个集合。我必须使用迭代器,我想知道我的代码或我的方法是否有问题。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)' 
+1

您应该提供您在提问时所得到的错误。 – Simple

回答

2

的最后一个参数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 << ", "; 
    } 
} 
+0

现在编译好了,但是M仍然是空的? fruits.txt是在正确的目录中,但它可能是我的构建设置或其他问题? – Cameron

+0

@Cameron哎呀抱歉。将'std :: cin'更改为'file'。请参阅编辑。 – Simple

+0

好的。还是行不通。这可能是我的IDE(使用Xcode)的问题。它在计算机上输出是否正确? – Cameron