微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

使用迭代器实现 stl 向量构造函数

如何解决使用迭代器实现 stl 向量构造函数

我正在尝试使用 C++98 实现 std::vector。

而且,我提到了 https://www.cplusplus.com/reference/vector/vector/vector/

因此,在构造函数中,我对向量进行了如下编码。

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())
{
...
}

但是,当我在 main 中测试该向量时,它并没有像我想要的那样工作。

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

我想调用 explicit vector (size_type n,const allocator_type& alloc = allocator_type()),但调用了带有迭代器的构造函数

所以,我的问题是

  1. 为什么会调用带有迭代器的构造函数
    这是因为“显式”吗?

  2. 我应该在 main() 中使用 'size_t' 来调用带有 'val' 的构造函数吗?
    或者,有没有办法检查迭代器?

很抱歉打扰你,但我真的不知道为什么会这样......

解决方法

实现通常会使用某种类型特征来启用/禁用迭代器版本,具体取决于迭代器类型是否真的是迭代器。

例如,它在概念上类似于:

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

(或更正确,以避免重新定义仅在默认模板参数中延迟的模板,如注释和此 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)

其中 IsIterator_v 是实现定义的类型特征,用于测试迭代器要求。

因此在您的构造函数示例 vector(3,100) 中,迭代器构造函数版本将不参与重载决议。

在 C++98 中,没有enable_if,但实现也会使用类似的概念检查。

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。