我在想象下面的场景:从一个空向量开始,向它推送一些int,然后使用它的大小来声明一个内置数组.
vector<int> vec; /* default init'ed */
for(decltype(vec.size()) i = 0; i != 10; ++i){
vec.push_back(i);
}
constexpr size_t sz = vec.size();
int arr[sz] = {}; /* list init, left out elem's are 0 */
Run Code Online (Sandbox Code Playgroud)
这个程序对我来说很直观(作为初学者).但它失败了以下消息:
testconstexpr2.cpp:22:34: error: call to non-constexpr function ‘std::vector<_Tp, _Alloc>::size_type std::vector<_Tp, _Alloc>::size() const [with _Tp = int; _Alloc = std::allocator<int>; std::vector<_Tp, _Alloc>::size_type = long unsigned int]’
testconstexpr2.cpp:23:13: error: size of array ‘arr’ is not an integral constant-expression
Run Code Online (Sandbox Code Playgroud)
我宁愿坚持使用内置数组,然后再去处理std :: array或dynamic array alloc.
到目前为止,我遇到了3种情况,其中数组保持为数组:(假设int arr[3][4];)
//
for(const auto &row : arr)
for(auto col : row)
cout << col << endl;
Run Code Online (Sandbox Code Playgroud)
问题:这是否会耗尽所有未将数组转换为指向单个元素的指针的情况?如果没有,是否有系统的方法来决定它?
语言律师明智,标准中的哪个条款禁止下面的代码:
int arr[] (10, 42);
Run Code Online (Sandbox Code Playgroud)
这将产生一个由10个元素组成的数组,每个元素都被初始化为42个元素.