C数组与指针:数组被视为变量,数组+0被视为指针

C array vs pointer : array is considered as a variable, array+0 is considered as a pointer?

本文关键字:数组 指针 变量      更新时间:2023-10-16

我在C++中创建了一个容器类,并且我有一个迭代器的构造函数,这样我就可以编写MyContainer<double> x(v.begin(), v.end()),其中vstd::vector<double>。我希望能够对c阵列做同样的事情,但是:

double array[3] =  {1., 2. , 3.};
MyContainer<double> x(array, array+3); // Doesn't work : no matching function for call to ‘MyContainer<double>::MyContainer(double [3], double*)’
MyContainer<double> x(array+0, array+3); // Work

问题的根源是什么?如何解决?

非常感谢。

不要接受对迭代器的引用,要按值进行引用。它试图传递对数组的引用;失败的表达式需要数组衰减为指针。

大概你有

template< typename Iter >
MyContainer( Iter const &first, Iter const &last );

但是你需要

template< typename Iter >
MyContainer( Iter first, Iter last );

迭代程序需要足够轻,以便传递值;所有的标准模板都是这样做的。

数组不能用作迭代器,因为它不能递增。存储是固定的。在像arr + 0这样的表达式中使用数组或通过值将其传递给函数时,它会隐式转换为指向其第一个元素的指针。但当通过引用传递时,这种转换不会发生。

array+0的结果是一个指针,而array本身不是指针,而是一个数组。您的构造函数没有接受数组和指针的重载,因此编译失败。

处理从数组生成开始迭代器和结束迭代器问题的惯用方法是使用begin(...)end(...)函数:

MyContainer<double> x(std::begin(array), std::end(array));

重载负责确定数组的末尾在哪里,从而使您无需向指针添加数组的长度。