yaro
yaro

Reputation: 173

how to add a float array to a float vector in c++

here is the problem. I have a float vector called vec:

std::vector<float> vec {1.1,2.2};

Now there is also a float array called, arr:

float arr[]={3.3 4.4 5.5};

So the question is how to add the array to the vector such that at the end we get {1.1 2.2 3.3 4.4 5.5} a longer float vector.

I tried this,

vec.insert(vec.begin(), arr,arr+3);

But the compiler gives a long error starting with

"error: no match in operator + in arr+3"

Upvotes: 1

Views: 3443

Answers (1)

sbarzowski
sbarzowski

Reputation: 2991

Something like that works for me:

std::vector<float> vec {1.1, 2.2};
float arr[] = {3.3, 4.4, 5.5};
vec.insert(vec.end(), arr, arr+3);

I guess you made some simple mistakes like:

  • You forgot to separate values in your float array by commas. In the question they are separated only by spaces and in effect arr is not successfully declared and you get your error.
  • If you want to add your values at the end, you have to vec.insert(vec.end(),...). The first argument is the iterator before which your range will be inserted.

Upvotes: 3

Related Questions