使用大括号符号C++填充动态数组

Fill dynamic array using curly bracket notation C++

本文关键字:C++ 填充 动态 数组 符号      更新时间:2023-10-16

c++中有没有一种方法可以填充像这样分配的数组

int **a = new int[4][2];

这样就可以像一样在一行中填充值

int a [4][2] = {{2,3,4},{5,6,7}};

您可以在C++11中使用通用初始化表示法:

int(*a)[2] = new int[2][2]{{1,2},{3,4}};

一个向量的向量可以工作,但只能在C++11中工作。我想你必须放弃的C兼容性

#include <vector>
int main()
{
   std::vector<std::vector<int>> v = {{2,3,4},{5,6,7}};   
}

如果编译器有足够的C++11支持,则首选std::array而不是C样式数组:

#include <array>
int main()
{
    std::array<std::array<int,3>,3> v = {1,2,3,4,5,6,7,8,9};
}