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?
std::dynarrayinstead ofstd::array.std::array, as they are not dynamically sizeable and not the right tool for this job. Either use anstd::vectoror anstd::dynarray, withvectorbeing more appropriate given your need for dynamic resizing. Related: stackoverflow.com/questions/19111028/stddynarray-vs-stdvector and stackoverflow.com/questions/756906/…a = tempwon't compile givenstack::operator=is only defined when assigning from another stack, and further even if you derive to access theprotectedcontainer andassignit may not change the capacity of your stacka. You're better off exposing thedeque(assuming you stick to the default container) and usingshrink_to_fitor the old swap-with-a-just-big-enough-stack/deque trick.