c++ - 为什么我不能创建流迭代器?
问题描述
我应该创建一个看起来像流迭代器的类,以便在增加我的类的对象时可以从输入流中读取。
我已经这样做了:
template<class T>
struct istrm_it{
istrm_it() = default;
istrm_it(std::istream& in) :
in_(in), val_(T()) {
in_ >> val_;
}
T val_;
std::istream& in_ = std::cin;
istrm_it& operator++() { in >> val_; return *this; };
istrm_it& operator++(int) { in_ >> val_; return *this; };
T operator*() { return val_; }
bool operator==(const istrm_it& rhs)const { return in_ == rhs.in_; }
bool operator!=(const istrm_it& rhs) const{ return in_ != rhs.in_; }
};
int main(){
istrm_it<int> it(std::cin), e;
cout << *it << endl; // ok
it++; // ok read the next value from the nput stream
vector<int> vi;
while (it != e) // the problem here
vi.push_back(*it++);
for (auto i : vi)
std::cout << i << ", ";
std::cout << std::endl;
std::cout << std::endl;
}
我得到什么:Severity Code Description Project File Line Suppression State
Error C2678 binary '!=': no operator found which takes a left-hand operand of type 'std::istream' (or there is no acceptable conversion)
解决方案
问题在于比较in_ != rhs.in_
(in_ == rhs.in_
以及)。你不能比较流。
相反,您需要保持某种“是结束迭代器”或“处于文件结束”状态,该状态在您到达文件结尾时设置,并且默认情况下在默认构造的迭代器对象中设置。