【发布时间】:2020-11-08 21:43:48
【问题描述】:
我是 C++ 编码的新手,在 C++ 入门第 5 版 Ex 3.42 中遇到了一个问题,要求我用向量的元素初始化一个数组。
所以,我写了这样的代码,但我不明白为什么 begin 函数会抛出没有匹配函数调用的错误。
我还尝试通过删除 begin 函数并使用 arr 初始化 *pbeg 来更正代码,
像这样,
int *pbeg = arr ;
而且它有效。
有人可以使用 begin 解释为什么以及我做错了什么吗?
#include <iostream>
#include <vector>
#include <iterator>
using std::cin ;
using std::cout ;
using std::endl ;
using std::vector ;
using std::begin ;
int main()
{
vector<int> ivec ;
int i ;
while(cin >> i)
ivec.push_back(i) ;
const auto len = ivec.size() ;
int arr[len] , *pbeg = begin(arr) ; // here it shows the error
for(auto c : ivec)
{
*pbeg = c ;
++pbeg ;
}
for(auto c : arr)
cout << c << "," ;
cout << endl ;
return 0 ;
}
【问题讨论】:
-
为什么要在这里使用VLA (
int arr[len]) 而不是vector?还有为什么要使用begin? -
您正在尝试使用可变长度数组 (VLA),即
int arr[len]。这不是标准 C++ 的特性;一些编译器接受它作为非标准扩展。std::begin适用于标准数组,但不适用于 VLA。 -
你不能只做你描述的,因为你描述的不是 C++ 语言的一部分。您所描述的某些变体适用于您的特定编译器,因为您的编译器支持该语言的某些非标准扩展,因此接受某些实际上不是有效的 C++ 程序的程序。
-
如果你在一本书中找到了这段代码,那么那本书没有教标准 C++。
-
在标准 C++ 中,数组维度必须是编译时常量。而
ivec.size()只能在运行时知道。在标准 C++ 中,std::vector应该用于需要具有动态(仅在运行时知道)大小的数组。