Use a template constructor:
template<class InputIterator>
BigInteger( InputIterator begin, InputIterator end )
This should be used like:
std::vector<int> v; //Fill with values
BigInteger( v.begin(), v.end() );
Pregunta
I have sample big integer class. It contains dynamic array of digits that comprise the big integer. I would like to construct objects of this class using 2 iterators (begin and end) in order I can pass digits from std::vector or std::list.
Some pseudocode illustrating my idea:
BigInteger(std::iterator begin, std::iterator end);
...
Usage:
std::vector<int> v;
// fill vector with digits
...
BigInteger b(v.begin(), v.end());
The question is: how to declare such constructor correctly? Also even is it possible?
Thanks!
Solución
Use a template constructor:
template<class InputIterator>
BigInteger( InputIterator begin, InputIterator end )
This should be used like:
std::vector<int> v; //Fill with values
BigInteger( v.begin(), v.end() );
Otros consejos
You can not use it simply!
If you declare the iterator types as templates, you can have this:
template <typename Itr>
BigInteger(Itr begin, Itr end)
{
}
or
BigInteger(std::vector<int>::iterator begin, std::vector<int>::iterator end)
{
}
But, how about std::iterator
. Well, std::iterator
is a template class and you should provide it's parameters and you should derive from it
class MyItr : public std::iterator<std::input_iterator_tag, int>
{
...
};
BigInteger(MyItr begin, MyItr end)
{
}
It's a long story! A possible definition of std::iterator
is
template<typename _Category, typename _Tp, typename _Distance = ptrdiff_t,
typename _Pointer = _Tp*, typename _Reference = _Tp&>
struct iterator
{
typedef _Category iterator_category;
typedef _Tp value_type;
typedef _Distance difference_type;
typedef _Pointer pointer;
typedef _Reference reference;
};
As you can see, it's just an empty class with some typedef
s. So, you have to implement operator*()
, operator->()
, begin()
, end()
, ... for derived iterator.