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!
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:
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);
.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With