std :: vector构造函数 - 为什么int而不是int*?

Joh*_*ing 1 c++ templates stl

我知道以下代码可以从数组构建一个stl向量:

  // the iterator constructor can also be used to construct from arrays:
  int myints[] = {16,2,77,29};
  std::vector<int> fifth (myints, myints + sizeof(myints) / sizeof(int) );
Run Code Online (Sandbox Code Playgroud)

(来源:cppreference)

使用的构造函数应该是

template <class InputIterator>
         vector (InputIterator first, InputIterator last,
                 const allocator_type& alloc = allocator_type());
Run Code Online (Sandbox Code Playgroud)

如果在上面的例子中<class InputIterator><int>,为什么InputIterator首先不是一个整数指针?数组名称"myints"衰变为指向第一个元素的指针,因为它等同于&myints [0]

我认为是正确的版本

template <class InputIterator>
         vector (InputIterator *first, InputIterator *last,
                 const allocator_type& alloc = allocator_type());
Run Code Online (Sandbox Code Playgroud)

Jos*_*eld 6

std::vector 声明如下:

template <class T, class Allocator = std::allocator<T>>
class Vector
{
  // ...
  typedef Allocator allocator_type;

  template <class InputIterator>
  vector(InputIterator first, InputIterator last,
         const allocator_type& = alocator_type());

  // ...
};
Run Code Online (Sandbox Code Playgroud)

请注意,类本身和构造函数都有模板参数.创建时std::vector<int>,int模板参数用于类模板参数T,确定向量的元素类型,而不是构造函数的元素类型InputIterator.

您允许InputIterator由编译器推导出(实际上,必须推导出构造函数的模板参数).你myints作为第一个参数传递给将要演绎的函数InputIterator.正如你所说,因为myints衰减到int*数组的第一个元素,然后InputIterator将被推断为一个int*,你得到以下构造函数的实例化:

vector (int* first, int* last,
        const allocator_type& alloc = allocator_type());
Run Code Online (Sandbox Code Playgroud)

InputIterator不是推断出来的int.它被推断为您作为第一个参数传递的完整类型(当然,第二个参数必须匹配).

这是有道理的,因为int它不是有效的输入迭代器.无论InputIterator推导出什么,都必须满足输入迭代器的要求.一个int*然而,是有效的.