const std::vector<sf::Vector2f>& getSnakePosition(const std::vector<Tail>& snakePosition)
{
std::vector<sf::Vector2f> ret;
for ( std::vector<Tail>::const_iterator iter; iter != snakePosition.end(); iter++ )
{
ret.emplace_back(iter->getPosition()); the program keeps crashing in this line
}
}
i tried to use debugger it says this line ret.emplace_back(iter->getPosition());
What you are doing is really just applying a function to each element of a vector to get the results in another vector. This is exactly what transform() does.
Also, I just realized you are returning a reference to a local variable. Don't do that.
1 2 3 4 5 6 7 8 9 10 11 12 13
#include <algorithm>
#include <iterator>
std::vector<sf::Vector2f> getSnakePosition( const std::vector<Tail>& snake )
{
std::vector<sf::Vector2f> snakePosition;
std::transform(
snake.begin(), snake.end(),
std::back_inserter(snakePosition),
[]( const Tail& tail ) { return tail.getPosition(); } // lambda functor to convert a Tail to a sf::Vector2f
);
return snakePosition;
}
Also, I just realized you are returning a reference to a local variable. Don't do that.
LOL! you just fix another of my problem thanks!. after the function, the ret is destroyed and accessing the returned vector of that function which reference that ret is wrong.
i havent read about lambda yet, but thanks for another suggestion