在函数内部初始化std :: array [英] Initializing std::array inside a function
问题描述
我想创建一个调整堆栈大小的函数.它将根据max的值创建一个更大或更小的新数组,然后将元素复制到该新数组中.
void resize(const int& max){std :: array< Item,max>温度for(int i = 0; i< n; i ++){temp.at(i)= a.at(i);}a =温度;}
我知道这不会运行,因为max不是一个常数表达式.我绝对不知道如何传递一个恒定的int值.我试过了:
void resize(constexpr int& max)//编译器说不能使int arg constexpr
我不想做constexpr void resize,因为我不需要在编译时对函数进行求值,而且该函数也无法正常工作.
注意:我知道如果我使用std :: vector可能会更容易,因为它可以调整大小,但是我想尝试使用std :: array.
我该怎么办?
我认为您错误地考虑了编译时常量和运行时常量.您不能以这种方式使用 std :: array
.您需要一个大小不是编译时常数的容器,该容器将为 std :: vector
.
如果您希望容器的大小在整个运行时保持恒定,则可以依靠自律(即:不要使用 push_back()
或 resize()
等等.)或者,您可以编写一个包装器类(例如,具有-std :: vector 作为成员的类)并仔细选择此类的方法,以免调整矢量的大小./p>
您也可以使用dynarray,但它已被c ++ 11(和c ++ 14,如果我没记错的话)拒绝了
PS:命名您的方法 resize()
然后说您想要常量大小的数组=)很奇怪您确实意识到,如果调用此方法,则实际上是在运行时更改了数组的大小,在这种情况下,为什么不使用std :: vector并对其进行处理呢?
I want to create a function that resizes a stack. It will create a new array with a larger or smaller size depending on the value of max, then copy the elements into that new array.
void resize(const int& max) {
std::array<Item, max> temp;
for (int i = 0; i < n; i++) {
temp.at(i) = a.at(i);
}
a = temp;
}
I know this will not run because max is not a constant expression. I absolutely don't know how to pass a constant int value. I tried:
void resize(constexpr int& max) //compiler says cannot make int arg constexpr
I don't want to do constexpr void resize because I don't need the function to be evaluated at compile time, and it didn't work anyway.
Note: I know this might be easier if I used std::vector because it's resizable, but I want to try to experiment with std::array.
What should I do?
I think you are mistaking compile-time constant and run-time constant. You cannot use std::array
in this way. You want a container whose size is not compile-time constant, and that would be std::vector
.
If you want your container's size to be constant throughout the runtime, you can either rely on self discipline (i.e : do not use push_back()
or resize()
etc..) Or you could write a wrapper class (.i.e a class that has-a std::vector
as a member) and choose the methods of this class carefully to never resize the vector.
You can also use dynarray but it has been rejected from c++11 (and c++14 If I recall correctly)
PS: it is quite weird to name your method resize()
and then say that you want constant-sized arrays =)
You do realize that if you call this method you are indeed changing the size of your array at runtime, in which case why not use std::vector and be done with it ?
这篇关于在函数内部初始化std :: array的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!