C++ Vector Range Constructor

Viewed 4017

I was looking over some C++ documentation when it occurred to me that the vector container doesn't have a constructor that 'easily' allows the user to pass a range of values - a min and a max - and have a vector constructed which has elements from min -> max. I thought this was odd so I tried writing my own and discovered it was non-trivial. Here's my solution.

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

template <typename T>
class MyIterator: public std::iterator<std::input_iterator_tag, int>
{

public:

  MyIterator(T val):value(val) {}
  MyIterator(const MyIterator & m):value(m.value) {}

  MyIterator& operator ++() 
  {
  ++value; 
    return *this; 
  }

  MyIterator operator ++(int) 
  { 
    MyIterator temp(*this); 
    operator ++();
    return temp; 
  }

  bool operator ==(const MyIterator & m) const { return value == m.value; }
  bool operator !=(const MyIterator & m) const { return !(value == m.value); }
  T& operator *() { return value; }

private:

  T value;

};

int main(int argc, char** argv)
{ 
  std::vector<int> my_vec(MyIterator<int>(100), MyIterator<int>(400));

  std::copy(my_vec.begin(), my_vec.end(), std::ostream_iterator<int>(std::cout, "\n"));

  return 0;
}

Does the new C++ have a solution for this?

2 Answers
Related