简体   繁体   English

在函数中传递ifstream迭代器

[英]passing ifstream iterator in function

Why is this code working? 为什么此代码有效? e iterator isn't point-assigned to anything. e迭代器不是点分配到任何东西。 How is implied that the function continues until the end of the fstream? 如何暗示该功能持续到fstream结束?

#include <vector>
#include <iostream>
#include <list>
#include <fstream>
#include <string>
#include <iterator>

using namespace std;

template<typename InputIterator>
void printRange(InputIterator first, InputIterator last)
{
    while (first != last)
    {
        std::cout << *first << endl;
        ++first;
    }
}
int main()
{
    vector<int> v = { 11, 24, 541 };
    printRange(v.begin(), v.end());
    cout << endl;
    list<double> lst = { 11.88, 21.4, 541.9 };
    printRange(lst.begin(), lst.end());
    cout << endl;
    ifstream ifs{ "strings.txt" };
    istream_iterator<string> i(ifs);
    istream_iterator<string> e;
    printRange(i, e);
}

strings.txt strings.txt

coding c++

The variable e is default constructed, so the 0-argument constructor is called. 变量e是默认构造的,因此将调用0参数构造函数。 And from the documentation : 并且从文档中

constexpr istream_iterator();

Constructs the end-of-stream iterator. 构造流结束迭代器。 This constructor is constexpr if std::is_trivially_default_constructible_v<T> is true. 如果std::is_trivially_default_constructible_v<T>为true,则此构造函数为constexpr。

So default constructing an istream_iterator constructs the end-of-stream iterator, which is exactly the value you need. 因此,默认构造一个istream_iterator构造一个流结束迭代器,这正是您需要的值。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM