std :: getline不接受std :: back_insert_iterator

时间:2012-03-15 11:05:38

标签: c++ stl

int main() { 
    std::deque<std::string> mydeque;
    std::back_insert_iterator<decltype(mydeque)> myback_insert_iterator(mydeque);
    std::ifstream myifstream("test.txt");
    while(std::getline(myifstream, *myback_insert_iterator)) {
    }
}

我只想将文本文件逐行读入字符串容器。 这会产生编译器错误:

  

C2784:无法推断'std :: basic_istream&lt; _Elem,_Traits&gt;的模板参数&安培;”来自'std :: ifstream'

怎么了?

2 个答案:

答案 0 :(得分:6)

尝试:

int main()
{
    std::deque<std::string> mydeque;
    std::ifstream myifstream("test.txt");

    std::string line;
    while(std::getline(myifstream, line)
    {
        mydeque.push_back(line);
    }
}

如果每行一个单词,您可以简化为:

int main()
{
    std::deque<std::string> mydeque;
    std::ifstream myifstream("test.txt");

    // Note: istream_iterator<T> uses std::istream& operator>>(std::istream&, T&) to
    //       read data from the stream. If `T` is a std::string this means it will
    //       read a single space separated word.

    std::copy(std::istream_iterator<std::string>(myifstream),
              std::istream_iterator<std::string>(),
              std::back_inserter(mydeque)
             );
}

如果每行包含多个单词并且您想使用后插入器,则需要定义一个类来读取可与迭代器一起使用的对象中的整行:

struct Line
{
    std::string data;
    operator std::string const&() const {return data;}

    friend std::istream& operator>>(std::istream& s, Line& dst)
    {
        return std::getline(s, dst.data);
    }
};

int main()
{
    std::deque<std::string> mydeque;
    std::ifstream myifstream("test.txt");

    std::copy(std::istream_iterator<Line>(myifstream),
              std::istream_iterator<Line>(),
              std::back_inserter(mydeque)
             );
}

或者我们可以使用构造函数:

int main()
{
    std::ifstream myifstream("test.txt");
    std::deque<std::string> mydeque(std::istream_iterator<Line>(myifstream),
                                    (std::istream_iterator<Line>()));
    // Note: Extra brace required around second iterator here
    //       This is to avoid the problem with the `Most Vexing Parse`
    //       Which would otherwise make this a function declaration

}

答案 1 :(得分:2)

getline需要一个字符串,而不是输出迭代器。您可以将myifstream包装到输入迭代器中并使用std::copy。像这样:

#include <deque>
#include <fstream>
#include <algorithm>
#include <iterator>

int main() {
    std::deque<std::string> mydeque;
    std::back_insert_iterator<decltype(mydeque)> myback_insert_iterator(mydeque);
    std::ifstream myifstream("test.txt");
    std::istream_iterator<std::string> i_it(myifstream), eos;
    std::copy(i_it, eos, myback_insert_iterator);
}