gpt4 book ai didi

c++ - 是否可以使用 new 运算符在 C++ 11 中初始化数组

转载 作者:太空狗 更新时间:2023-10-29 19:59:08 24 4
gpt4 key购买 nike

大家好,我想像这样在 C++ 中初始化一个数组

int array[10]={1,2,3,4,5,6,7,8,9,10};

但我正在使用 new 运算符。

我知道我可以像下面那样做,然后迭代并分配值

shared_ptr<int[]> l (new int[7]);

但如果有某种方法可以在新命令期间初始化它,我真的很高兴

像这样的东西 shared_ptr<int[]> l (new int[7] ={1,2,3,4,5,6,7});但遗憾的是,这不是一个有效的语法。

同样在 C++ 11 标准中添加了一个新的 STL 容器数组,有人可以告诉我使用普通数组还是 STL 数组可以实现吗

最佳答案

C++11 为容器提供了一个 initializer_list,其工作方式如下:

std::vector<int> array = {1,2,3,4,5};

vector动态数组类。


这是您的 shared_ptr 版本:

std::shared_ptr<int> ptr(new int[5]{1,2,3,4,5}, std::default_delete<int[]>());

关于c++ - 是否可以使用 new 运算符在 C++ 11 中初始化数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15183671/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com