[ create a new paste ] login | about

Link: http://codepad.org/DKF5WRfT    [ raw code | output | fork ]

C++, pasted on Jun 25:
#include <iostream>
#include <stdexcept>
#include <string>
#include <vector>

using namespace std;

template <typename T>
class Iterator
{
public:
  typedef typename T::iterator IterType;
  Iterator(T& source) :
    begin(source.begin()),
    end(source.end()),
    current(begin)
  {
  }

  bool hasNext() const
  {
    return current != end;
  }

  typename iterator_traits<typename T::iterator>::reference next()
  {
    if (current == end)
    {
      throw range_error("Used next() after hasNext() returned false!");
    }
    return *current++;
  }

private:
  IterType begin;
  IterType end;
  IterType current;
};

int main()
{
  vector<string> temp;
  temp.push_back("Some text 1");
  temp.push_back("Some text 2");

  Iterator<vector<string> > iter(temp);
  while(iter.hasNext())
  {
    cout << iter.next() << endl;
  }


  string temp2 = "another test string";
  Iterator<string> iter2(temp2);
  while(iter2.hasNext())
  {
    cout << iter2.next() << endl;
  }

  try
  {
    iter2.next();
    cout << "next should have thrown" << endl;
  }
  catch(...)
  {
    cout << "next threw as expected" << endl;
  }
}


Output:
Some text 1
Some text 2
a
n
o
t
h
e
r
 
t
e
s
t
 
s
t
r
i
n
g
next threw as expected


Create a new paste based on this one


Comments: