获取 c++ 中具有恒定长度的数组的迭代器
Getting iterator for an array with a constant length in c++
我在另一个堆栈溢出帖子(使用模板推导传递数组时出现可变长度数组错误(上读到,应该可以执行以下操作:
#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);
相关文章:
- 迭代器库中的 std::size() 不适用于传递给函数的 C 样式数组
- 自定义 STL 兼容迭代器,用于迭代 2D 数组类的列
- 在C++中使用 for 循环的数组迭代
- 获取 c++ 中具有恒定长度的数组的迭代器
- 为自定义数组实现迭代器
- 原始数组和 std::array 在 clang++ 和 VC++ 上的不同迭代器行为
- 有没有办法创建一个花哨的迭代器和相应的新数组,以便检查每个索引的索引值的条件?
- C 迭代器范围使用指针到数组
- 是否可以在 C 数组中使用迭代器?
- 为矩阵创建动态数组,以循环迭代器命名
- 使用迭代器将向量复制到数组中
- 数组迭代器不是可取消引用的错误
- 元素级多维数组迭代,与存储顺序无关
- 多维数组迭代效率
- std::不带模板的数组迭代器范围
- 在多线程代码中缓存友好的数组迭代模式
- 用1个循环解释二维数组迭代
- 数组迭代器中的hasNext()方法
- 兼容STL的两个数组迭代器
- 对于循环数组迭代,if循环测试索引是否为真/假,计算结果不正确