2

Sorry for the question, I have been doing Python and JS too much and am coming back to C++ now to assign an array.

How can it be done easier than this:

float* d1 = (float*)calloc(4,sizeof(float));
d1[0] = 1;
d1[1] = 2;
d1[2] = 3;
d1[3] = 4;

I am used to d1 = [1,2,3,4] and cannot wrap my head around it...

2

3 Answers 3

6

I see the following options for creating an array of floats.

Option 1

Use a regular array.

float d1[] = {1.0f, 2.0f, 3.0f, 4.0f};

or

float d1[4] = {1.0f, 2.0f, 3.0f, 4.0f};

Option 2

Use std::array.

std::array<float, 4> d1{1.0f, 2.0f, 3.0f, 4.0f}

Option 3

Use std::vector.

std::vector<float> d1{1.0f, 2.0f, 3.0f, 4.0f}

Unless there is a strong reason, prefer to use std::array or std::vector. std::array is appropriate if you know the size of the array at compile time. std::vector is appropriate if you don't know the size of the array at compile time.

One of the main benefits of using std::array or std::vector is that you have the ability to find out the size of array when the variable is used in a function call. If you use a regular array, the array decays to a pointer. You have to pass the size in another argument to help the function prevent accessing the array using an out of bounds index.

Sign up to request clarification or add additional context in comments.

Comments

1

Try this code out :

float array[] = {1.0f,2.0f,3.0f,4.0f};

This code creates a simple array of 4 elements . Upon initialization , the arrays is the following contents : 1,2,3,4 . Hope this helps .

Comments

0

If the values are known at compile time

 float d1[4] = {1.0f, 2.0f, 3.0f, 4.0f};

or

 std::array<float, 4>  d1 {1.0f, 2.0f, 3.0f, 4.0f};    // since C++11

The simple way is, assuming values are generated at run time,

 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>

or (if the number of elements is not known until run time)

 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);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.