轻松C++阵列分配
Easy C++ array assignment
很抱歉这个问题,我一直在做Python和JS,现在回到C++分配一个数组。
怎么能比这更容易完成:
float* d1 = (float*)calloc(4,sizeof(float));
d1[0] = 1;
d1[1] = 2;
d1[2] = 3;
d1[3] = 4;
我习惯了d1 = [1,2,3,4]
,无法绕开它......
我看到以下用于创建float
数组的选项。
选项 1
使用常规数组。
float d1[] = {1.0f, 2.0f, 3.0f, 4.0f};
或
float d1[4] = {1.0f, 2.0f, 3.0f, 4.0f};
选项 2
使用std::array
。
std::array<float, 4> d1{1.0f, 2.0f, 3.0f, 4.0f}
选项 3
使用std::vector
.
std::vector<float> d1{1.0f, 2.0f, 3.0f, 4.0f}
除非有充分的理由,否则最好使用std::array
或std::vector
。 如果您在编译时知道数组的大小,则std::array
是合适的。 如果您在编译时不知道数组的大小,则std::vector
是合适的。
使用std::array
或std::vector
的主要好处之一是,当在函数调用中使用变量时,您可以找出数组的大小。如果使用常规数组,则数组将衰减为指针。您必须在另一个参数中传递大小,以帮助函数防止使用越界索引访问数组。
试试这段代码:
float array[] = {1.0f,2.0f,3.0f,4.0f};
此代码创建一个包含 4 个元素的简单数组。初始化时,数组是以下内容1,2,3,4
:希望这有帮助.
如果值在编译时已知
float d1[4] = {1.0f, 2.0f, 3.0f, 4.0f};
或
std::array<float, 4> d1 {1.0f, 2.0f, 3.0f, 4.0f}; // since C++11
简单的方法是,假设值是在运行时生成的,
std::array<float, 4> d1; // or float d1[4]
for (int i = 0; i < 4; ++i) d1[i] = i+1.0f;
// or, instead of the loop, since C++11
std::iota(std::begin(d1), std::end(d1), 1.0f); // iota() specified in <numeric>
或(如果元素的数量直到运行时才知道(
std::vector<float> d1(number);
for (int i = 0; i < number; ++i) d1[i] = i+1.0f;
// or, instead of the loop, since C++11
std::iota(d1.begin(), d1.end(), 1.0f);
相关文章:
- 二维阵列的动态分配
- 为什么删除分配的阵列会导致内存错误?
- 新的阵列分配
- 分配给阵列时出现分段错误?黑客排名 2D 阵列 - DS.
- 分配/访问2d阵列,使得2d子块是连续的
- 重新分配2D阵列并删除旧阵列
- 轻松C++阵列分配
- 英特尔并行工作室 2015 C++中的 2D 动态分配全局阵列
- 解除分配此特定 2D 阵列的内存
- 我可以在堆栈上分配`std :: array`阵列,而不知道编译时大小
- 通过"Value Template Argument"与常规阵列在堆栈中分配内存
- C - 将所有分配的双阵列对齐至32 bytes
- 重新分配指针阵列的一部分的安全方法
- 动态分配'string'阵列
- 未分配阵列上的编号
- 与其所有者一起分配阵列的正确方法
- 为 C++ + OpenGL + QT 分配阵列
- 分配阵列时bad_alloc
- C++中2D动态内存分配阵列中的空闲分配内存
- C++中的2D动态内存分配阵列