Reputation: 1476
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?
Upvotes: 5
Views: 4385
Reputation: 153830
For C++11 there was no substantial work on changing the algorithms or containers to make them easier usable (there are a couple of new algorithms and the containers were made aware of allocators and rvalues). Neither is there a substantial change for C++14.
There is some hope for C++17, though: the Ranges Study Group is looking at concepts to make the algorithms and containers easier to use. That said, it isn't clear where that journey will travel to.
Upvotes: 1
Reputation: 409176
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
.
Upvotes: 4