Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ - Vector of Float Arrays

Tags:

c++

arrays

vector

I'm currently attempting to create a vector that holds float arrays. I am having a diffcult time.

I have the following code:

float testArray[4] = {20, -3.14/2, 5, -3.14/2};
std::vector<float[4]> inputVector;
std::vector<float[4]>::iterator it = inputVector.begin();
inputVector.insert(it, testArray);

I keep getting an error say "array must be initialized with a brace-enclosed initializer" and "invalid array assignment". I tried this same code with a vector of ints (as opposed to a vector of array) and did not have any issue.

I believe there is an underlying issue that I don't understand.

Any help is appreciated!

like image 368
Izzo Avatar asked Feb 08 '23 13:02

Izzo


2 Answers

Use std::array. C-style arrays shouldn't generally be used in modern C++ code.

#include <vector>
#include <array>

int main()
{
  std::array<float, 4> testArray{{20, -3.14/2, 5, -3.14/2}};
  std::vector<std::array<float, 4>> inputVector;
  std::vector<std::array<float, 4>>::iterator it = inputVector.begin();
  inputVector.insert(it, testArray);
}

Read these questions/answers for more information:

  • "Now that we have std::array what uses are left for C-style arrays?"
  • "c++11 std::array vs static array vs std::vector"

Note that this will copy the array and all its contents. If you want to refer to the existing testArray instance, create an std::vector<std::array<float, 4>*> and take the address of the instance when inserting it in the vector: inputVector.insert(it, &testArray);.

like image 117
Vittorio Romeo Avatar answered Feb 11 '23 22:02

Vittorio Romeo


How about this :-

float t[4] = {20, -3.14/2, 5, -3.14/2};
float *testArray=t;
std::vector<float*> inputVector;
std::vector<float*>::iterator it = inputVector.begin();
inputVector.insert(it, testArray);

It would be better if you use std::array<float, 4> instead of in-built arrays. The problem with your previous code was that you were attempting something like :-

float a[4] {1.1, 2.2, 3.3, 4.4};
float b[4] = a;   // illegal conversion of float[] to float*

Hence your code used to fail

like image 36
Ankit Acharya Avatar answered Feb 11 '23 21:02

Ankit Acharya