I just wonder if is possible to new and initialize a std::vector
at
the same time, something like, do the two things in one line?
Yes, you can, via std::initializer_list
constructor10 of std::vector
constexpr vector( std::initializer_list<T> init,
const Allocator& alloc = Allocator() ); (since C++20)
With you can write
std::vector<int>* vec = new std::vector<int>{3, 4};
Because I need a vector that create on heap!
The terms we use in C++ are automatic and dynamic storage. In most of the cases, you do not require the std::vector<int>
to be allocated dynamically, rather the elements to be there. For this, you need simply a vector of integers.
std::vector<int> vec {3, 4};
However, if you're meant for a multidimensional vector, then I will suggest having a vector of vector of inters:
std::vector<std::vector<int>> vec{ {3, 4} };
When the inner vector has the same number of length, keep a single std::vector
and manipulate the indexes for acting as a two-dimensional array.
In both cases, the std::vector
in the background does the memory management for you.