Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
237 views
in Technique[技术] by (71.8m points)

c++ - implement stl vector constructor using iterator

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...

question from:https://stackoverflow.com/questions/65931743/implement-stl-vector-constructor-using-iterator

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...