Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ Vector Range Constructor

Tags:

c++

vector

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?

like image 430
user2699298 Avatar asked Dec 30 '13 14:12

user2699298


Video Answer


1 Answers

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.

like image 194
Some programmer dude Avatar answered Sep 24 '22 14:09

Some programmer dude