Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

implement stl vector constructor using iterator

Tags:

c++

I'm trying to implement std::vector with C++98.

And, I referred https://www.cplusplus.com/reference/vector/vector/vector/

So, in constructor, I coded the vector like following.

explicit vector (size_type n, const value_type& val = value_type(),
                 const allocator_type& alloc = allocator_type())
{
...
}

template <class InputIterator>
         vector (InputIterator first, InputIterator last,
                 const allocator_type& alloc = allocator_type())
{
...
}

But, when I tested that vector in main, it didn't work as I want.

int main(void)
{
    vector<int> vec(3, 100);
}

I wanted to call explicit vector (size_type n, const value_type& val = value_type(), const allocator_type& alloc = allocator_type()), but the constructor with iterator was called.

So, my question is that

  1. Why the constructor with iterator is called?
    Is this happened because of 'explicit'?

  2. Should I use 'size_t' in main() to call the constructor with 'val'?
    Or, is there any way to check iterator?

sorry to bother you, but I really don't know why this happened...

like image 680
yhshin Avatar asked Nov 06 '22 03:11

yhshin


People also ask

How do you initialize a vector iterator?

You can initialize a vector by using an array that has been already defined. You need to pass the elements of the array to the iterator constructor of the vector class. The array of size n is passed to the iterator constructor of the vector class.

How do I print a vector iterator?

To print all elements of a vector, we can use two functions 1) vector::begin() and vector::end() functions. vector::begin() function returns an iterator pointing to the first elements of the vector. vector::end() function returns an iterator point to past-the-end element of the vector.


1 Answers

The implementation will normally use some kind of type traits to enable/disable iterator version, depending on if the iterator type is really an iterator or not.

For example, it would conceptually be something like:

template <class InputIterator, typename = enable_if_t<IsIterator_v<InputIterator>>
vector(InputIterator first, InputIteratorLast)

(or more correct to avoid redefinition of templates which defere only in default template arguments, as stated in comments and under this notes:):

// this is more the way it's actually practically implemented
template <class InputIterator, enable_if_t<IsIterator_v<InputIterator>, int> = 0>
    vector(InputIterator first, InputIteratorLast)

where IsIterator_v is implementation defined type trait for testing iterator requirement.

So in your constructor example vector(3, 100) the iterator constructor version will then not participate in overload resolution.

In C++98 there is no enable_if, but also then the implementation would use similar kind of concept checks.

like image 123
StPiere Avatar answered Dec 07 '22 00:12

StPiere