Home > Software design >  Is it possible to initialize new std::vector in one line?
Is it possible to initialize new std::vector in one line?

Time:09-25

I just wonder if it is possible to new and initialize a std::vector at the same time, something like, do the two things in one line:

std::vector<int>* vec = new std::vector<int>(){3, 4};

instead of, first:

std::vector<int>* vec = new std::vector<int>();

then:

vec->push_back(3);
vec->puch_back(4);

CodePudding user response:

This std::vector<int>() calls the default constructor, but there are other constructors: https://en.cppreference.com/w/cpp/container/vector/vector.

There is also a constructor that takes a std::initializer_list<T> that you can use: std::vector<int>({3,4}).

This is no different whether you use new to allocate the vector or not. However, there is almost never a good reason to allocate a std::vector via new, because the vector already does store its elements in dynamically allocated memory.

CodePudding user response:

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.

  • Related