C数组与指针:数组被视为变量,数组+0被视为指针
C array vs pointer : array is considered as a variable, array+0 is considered as a pointer?
我在C++中创建了一个容器类,并且我有一个迭代器的构造函数,这样我就可以编写MyContainer<double> x(v.begin(), v.end())
,其中v
是std::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));
重载负责确定数组的末尾在哪里,从而使您无需向指针添加数组的长度。
相关文章:
- 添加到数组指针
- C++语法差异:二维和一维数组(指针算术)
- 数组指针表示法C++(移动数组时)
- 复制后删除原始数组指针将前 3 个字节设置为 0
- C++访问指向结构的指针中的类数组指针
- C++编译时使用 constexpr 字符数组指针分配静态数组?
- std::flush可以用于将对象指针转换为其封闭数组指针吗
- 创建<int>对整数数组指针的矢量引用 (C++)
- 将 2D 数组指针传递给 C++ 中的函数
- 创建指针是否超过非数组指针的末尾,而不是从 C++17 中的一元运算符和未定义的行为派生?
- 队列数组指针 (C++)
- C++数组指针上的删除操作
- 对于循环不循环和检测字符数组 [指针和字符数组]
- 如何初始化数组指针对象
- 如何正确传递 2D 数组指针作为参数
- 从数组指针中获取怪异的数字
- 初始化std :: unique_ptr作为原始数组指针的初始化
- 将结构数组指针从C#传递到C
- STD :: Sort将数组指针设置为NULL
- C++数组指针错误无法将“int*”转换为“int**”