C++定义数组类型

typedef osg::Vec3 VectorPoints[8];

VectorPoints _worldCorners;

 

 

typedef VectorPoints (ChildrenCorners) [4];

ChildrenCorners _childrenCorners;//相当于定义了二维数组

 

 

 

C++定义数组可以通过多种方式实现,具体取决于需求,例如静态数组、动态数组或使用标准库容器。以下是一些常见的定义数组的语法示例: ### 静态数组 静态数组是在编译时分配固定大小的数组。其大小必须是常量表达式。 ```cpp const int size = 5; int myStaticArray[size] = {1, 2, 3, 4, 5}; // 定义并初始化一个静态数组 ``` ### 动态数组 动态数组是在运行时根据需要分配内存的数组,通常使用 `new` 运算符实现。 ```cpp int length; std::cout << "Enter the size of the array: "; std::cin >> length; int* myDynamicArray = new int[length]; // 使用 new 分配动态数组 // 使用完数组后,记得释放内存 delete[] myDynamicArray; ``` ### 使用 `std::array` `std::array` 是 C++11 引入的标准库容器,它提供了一个固定大小的数组,并具有更好的安全性。 ```cpp #include <array> std::array<int, 5> myArray = {1, 2, 3, 4, 5}; // 定义并初始化一个 std::array ``` ### 使用 `std::vector` `std::vector` 是动态数组的实现,可以根据需要自动调整大小。 ```cpp #include <vector> std::vector<int> myVector = {1, 2, 3, 4, 5}; // 定义并初始化一个 std::vector myVector.push_back(6); // 添加元素到数组末尾 ``` ### 多维数组 多维数组可以通过嵌套定义实现,例如二维数组: ```cpp int matrix[3][3] = { {1, 2, 3}, {4, 5, 6}, {7, 8, 9} }; ``` ### 示例代码整合 以下是一个完整的示例,展示如何定义和使用不同类型数组: ```cpp #include <iostream> #include <array> #include <vector> int main() { // 静态数组 const int size = 5; int staticArray[size] = {1, 2, 3, 4, 5}; // 动态数组 int length; std::cout << "Enter the size of the dynamic array: "; std::cin >> length; int* dynamicArray = new int[length]; for (int i = 0; i < length; ++i) { dynamicArray[i] = i * 2; } delete[] dynamicArray; // std::array std::array<int, 5> stlArray = {1, 2, 3, 4, 5}; // std::vector std::vector<int> vectorArray = {1, 2, 3, 4, 5}; vectorArray.push_back(6); // 二维数组 int matrix[3][3] = { {1, 2, 3}, {4, 5, 6}, {7, 8, 9} }; return 0; } ``` 上述方法涵盖了 C++定义数组的主要方式,开发者可以根据具体场景选择适合的实现形式。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值