是否可以在一行中初始化 new std::vector ?

Is it possible to initialize new std::vector in one line?

我只是想知道是否可以同时 new 和初始化一个 std::vector,比如,在一行中做两件事:

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

而不是,首先:

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

然后:

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

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?

是的,你可以,通过 std::initializer_list 构造函数 10 of std::vector

constexpr vector( std::initializer_list<T> init,
                  const Allocator& alloc = Allocator() ); (since C++20)

有了你就可以写

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

Because I need a vector that create on heap!

我们在 C++ 中使用的术语是 automatic and dynamic storage。在大多数情况下,您不需要动态分配 std::vector<int>,而是要求元素在那里。为此,您只需要一个整数向量。

std::vector<int> vec {3, 4};

但是,如果您打算使用多维向量,那么我建议您使用一个向量的向量:

std::vector<std::vector<int>> vec{ {3, 4} };

当内向量长度相同时,保持单个std::vector并操作索引作为二维数组

在这两种情况下,后台的 std::vector 都会为您进行内存管理。

这个std::vector<int>()调用了默认的构造函数,但是还有其他的构造函数:https://en.cppreference.com/w/cpp/container/vector/vector.

还有一个带有 std::initializer_list<T> 的构造函数,您可以使用:std::vector<int>({3,4}).

无论是否使用new分配向量,这都没有什么不同。但是,几乎没有什么好的理由通过 new 分配 std::vector,因为向量已经将其元素存储在动态分配的内存中。