0

I'm trying to make the following code to work

auto createMyArray = []() {
  float foo[] = {0.0f, 1.5f, 2.0f};
  return foo;
};

auto myArray = createMyArray();

std::vector<float> myVector;

// fatal error: no matching function for call to 'begin'
myVector.insert(myVector.end(), std::begin(myArray), std::end(myArray));

The issue is that createMyArray returns a pointer to the array and I'm not sure if it will be a good idea to try dereference it.

Also I'm getting the following warning

warning: address of stack memory associated with local variable 'foo' returned [-Wreturn-stack-address]
    return foo;

Which has sense because I'm not using new to create the array since I want to avoid heap allocations.

ellipticaldoor
  • 1,122
  • 11
  • 24

3 Answers3

1

The modern C++ way of dealing with such arrays is to use std::array. That should avoid the problems you are facing.

Using a native C array like you do gets you into allocation-related problems which you should avoid. The compiler warning you are seeing is not to be taken lightly (like any warning). It tells you that foo points to memory that falls out-of-scope outside your lambda. It is quite likely to be overwritten by the myVector object you create after the call to createMyArray() and any further reference to foo's elements may give you garbage.

Apart from that see the helpful answers here: How do you copy the contents of an array to a std::vector in C++ without looping?

ypnos
  • 50,202
  • 14
  • 95
  • 141
1

After exiting the lambda expression the local array will not be alive. So the code has undefined behavior.

But there is no need to use a lambda to insert an initializer list in a vector.

Here is a demonstrative program.

#include <iostream>
#include <vector>
#include <iterator>

int main() 
{
    std::vector<float> myVector;
    
    myVector.insert( std::end( myVector ), {0.0f, 1.5f, 2.0f} );
    
    for ( const auto &item : myVector ) std::cout << item << ' ';
    std::cout << '\n';
    
    return 0;
}

The program output is

0 1.5 2
Vlad from Moscow
  • 301,070
  • 26
  • 186
  • 335
0

You can use std::back_inserter to copy elements into the vector appending at the end

std::copy(myArray, myArray + 3, std::back_inserter(myVector));

Or

myVector.insert(myVector.end(), myArray, myArray + 3);

By the way the array created in lamba function is stack allocated, which means array will no longer exist after the execution of lamba function, instead use dynamic memory allocation using new or std::array

Harry
  • 2,177
  • 1
  • 19
  • 33
  • 2
    It is not true that the insert() method is not applicable. OP is just using it wrong (coupled with wrong use of stack-allocated native array). – ypnos Dec 28 '20 at 15:15