簡體   English   中英

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 << ", ";
    }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM