C++ istream_迭代器将文件中的值读取到集合中

C++ istream_迭代器将文件中的值读取到集合中,c++,set,ifstream,C++,Set,Ifstream,我很难将istream_迭代器用于我需要的目的。我有一个文件,我想逐行读取到一个集合中。我必须使用迭代器,我想知道我的代码或方法是否有问题 非常感谢你的帮助。下面是我正在编写的代码的简化版本: main.cpp #include <iostream> #include <fstream> #include <string> #include <set> using namespace std; int main() { ifstrea

我很难将istream_迭代器用于我需要的目的。我有一个文件,我想逐行读取到一个集合中。我必须使用迭代器,我想知道我的代码或方法是否有问题

非常感谢你的帮助。下面是我正在编写的代码的简化版本:

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;
}
错误:

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 << ", ";
    }
}
#包括
#包括
#包括
#包括
#包括
#包括
使用名称空间std;
int main()
{
ifstream文件(“fruits.txt”);
设M;
复制(istream_迭代器(文件),
istream_迭代器(),
插入器(M,M.end());
用于(自动常数和值:M)
{

coutcopy
的最后一个参数必须是迭代器,而不是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 << ", ";
    }
}
#包括
#包括
#包括
#包括
#包括
#包括
使用名称空间std;
int main()
{
ifstream文件(“fruits.txt”);
设M;
复制(istream_迭代器(文件),
istream_迭代器(),
插入器(M,M.end());
用于(自动常数和值:M)
{

您是否应该提供您提问时遇到的错误。您应该提供您提问时遇到的错误。它现在可以编译,但M仍然为空?fruits.txt在正确的目录中,但可能是我的构建设置或其他问题吗?@Cameron oops对不起。将
std::cin
更改为
文件
。请参阅edit.ok。仍然不工作。这可能是我的IDE(使用Xcode)的问题。它在你的计算机上输出正确吗?@Cameron在我的计算机上工作。我使用
cin
进行测试,但不是
文件,这就是为什么输入错误滑入。我刚刚在VS2015上使用一个文件进行了测试,它也可以工作。Hmm将对此进行研究。谢谢你的帮助!它现在编译良好,但M仍然为空?fruits.txt在正确的目录中,but可能是我的生成设置有问题还是其他问题?@Cameron oops抱歉。请将
std::cin
更改为
file
。请参阅编辑。好的。仍然不工作。这可能是我的IDE(使用Xcode)有问题。它在您的计算机上输出正确吗?@Cameron在我的计算机上工作。我使用
cin
进行测试,但不是
文件
,这就是为什么输入错误出现的原因。我刚刚在VS2015上使用一个文件进行了测试,它也可以工作。嗯,将对此进行研究。感谢您的帮助!