dylanin1999

导航

C++ istream_iterator的源码与使用方法分析

最近在看C++ STL的源码,看的主要是gnu2.9版本的源码。

其中看到了istream_iterator的实现源码,源码如下:

template <class T, class Distance = ptrdiff_t> 
class istream_iterator {
  friend bool
  operator== __STL_NULL_TMPL_ARGS (const istream_iterator<T, Distance>& x,
                                   const istream_iterator<T, Distance>& y);
protected:
  istream* stream;
  T value;
  bool end_marker;
  void read() {//根据*stream来确定end_marker
    end_marker = (*stream) ? true : false;
    if (end_marker) *stream >> value;
    end_marker = (*stream) ? true : false;
  }
public:
  typedef input_iterator_tag iterator_category;
  typedef T                  value_type;
  typedef Distance           difference_type;
  typedef const T*           pointer;
  typedef const T&           reference;

  istream_iterator() : stream(&cin), end_marker(false) {}
  istream_iterator(istream& s) : stream(&s) { read(); }
  reference operator*() const { return value; }
#ifndef __SGI_STL_NO_ARROW_OPERATOR
  pointer operator->() const { return &(operator*()); }
#endif /* __SGI_STL_NO_ARROW_OPERATOR */
  istream_iterator<T, Distance>& operator++() { 
    read(); 
    return *this;
  }
  istream_iterator<T, Distance> operator++(int)  {
    istream_iterator<T, Distance> tmp = *this;
    read();
    return tmp;
  }
};

istream_iterator的源码并不复杂,遇到的问题主要是在于vs studio中的使用上。先放上,我的代码:

#include <iostream>
#include <iterator>
#include <vector>

int main()
{
	std::cout << "请输入vector的初始化元素值:";
	std::istream_iterator<double> eos; //终止符 end of stream
	std::istream_iterator<double> itt(std::cin);
	std::vector<double> vec;
	while (itt!=eos)
	{
		vec.push_back(*itt);
		itt++;
	}
	std::cout << "value: ";
	for (auto a : vec)
	{
		std::cout << a << " ";
	}
	std::cout << std::endl;
	return 0;
}

可以看到在使用istream_iterator的时候,我们需要将其绑定std::cin以及还需要额外定义一个没有赋初值的'eos'。

那么恰恰问题就出在这里,EOS在Windows上的值到底是啥?是空格、回车还是另有其值?

最后发现,终止符的输入方法为Ctrl+Z

在我们输入完元素后,我们输入Ctrl+Z后,再需要输入换行符(),才能使得istream_iterator识别到终止符,从而终止输入。

输入效果如下:

这算是一个小小的坑,记录一下!马上也要完成STL的源码阅读了,也算是留作纪念了吧!

posted on 2022-08-13 16:15  DylanYeung  阅读(91)  评论(0编辑  收藏  举报