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
Why the constructor with iterator is called?
Is this happened because of 'explicit'?
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...
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.
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.
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.
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