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?
In C++11 there is the std::iota
function. Otherwise you have e.g. std::fill
and std::fill_n
, or std::generate
and std::generate_n
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With