获取 c++ 中具有恒定长度的数组的迭代器

Getting iterator for an array with a constant length in c++

本文关键字:数组 迭代器 c++ 获取      更新时间:2023-10-16

我在另一个堆栈溢出帖子(使用模板推导传递数组时出现可变长度数组错误(上读到,应该可以执行以下操作:

#include <iostream>
int input() {
int a;
std::cin>>a;
return a;
}
int main()
{
const int b = input();
int sum[b];
std::begin(sum);
}

除了它似乎不起作用之外,我仍然收到类似的错误。

In function 'int main()': 
16:17: error: no matching function for call to 'begin(int [b])' 
16:17: note: candidates are:

然后是有关它可能适合的模板的信息。

仅当sum是常规数组时才能使用std::begin(sum),而不能在它是可变长度数组时使用。

以下就可以了。

const int b = 10;
int sum[b];
std::begin(sum);

在您的情况下,b在编译时是未知的。对于长度在编译时未知的数组,最好使用std::vector而不是依赖特定于编译器的扩展。以下就可以了。

const int b = input();  // You can use int b, i.e. without the const, also.
std::vector<int> sum(b);
std::begin(sum);