How do I achieve the following:
std::vector<int> vec = { 1, 2, 3 };
const int N = vec.size();
// Now create NxN 2D array.
First, I know I could do it with new
but I'd have to remember to delete it later, and I'd rather not have to handle deallocation of memory if possible.
Second, I can't declare the 2D array on the stack because N is not (and can't be in this case) a constant expression. (In any case I'm using VS2013 and it doesn't support constexpr
.)
Third, I can't (or maybe don't know how to) use std::array
because apparently "a local variable cannot be used as a non-type argument". (I copy-pasted this from the VS2013 compile dialogue and have little understanding regarding this point).
Fourth, I'm thinking of using unique_ptr
. The problem is, I know how to use unique_ptr
for a 1D array, like std::unique_ptr<int> arr{ new int[N] }
, but can't figure out how to do it for a 2D array.
Lastly, I know I can always write my own thin wrapper around a C-style array that's always created on the heap, or write my own 2D array class. But is there a native or standard library way of doing this in C++ (C++11)?