轻松C++阵列分配

Easy C++ array assignment

本文关键字:分配 阵列 C++ 轻松      更新时间:2023-10-16

很抱歉这个问题,我一直在做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::arraystd::vector。 如果您在编译时知道数组的大小,则std::array是合适的。 如果您在编译时不知道数组的大小,则std::vector是合适的。

使用std::arraystd::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);