program crashes in emplace back

1
2
3
4
5
6
7
8
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());
It is crashing because the iterator iter is not initialized; the true error is on line 4:

1
2
3
4
5
6
7
8
9
10
11
12
13
const std::vector<sf::Vector2f>& getSnakePosition(const std::vector<Tail>& snakePosition)
{
    std::vector<sf::Vector2f> ret;
    for ( std::vector<Tail>::const_iterator iter = snakePosition.begin(); 
          iter != snakePosition.end(); 
          iter++ )
    {
        ret.emplace_back(iter->getPosition()); 
    }

    // Also, don't forget to return value
    return ret;
}

[edit] BTW, you could rewrite that with a ranged-for loop:

1
2
3
4
5
6
const std::vector<sf::Vector2f>& getSnakePosition(const std::vector<Tail>& snakePosition)
{
    std::vector<sf::Vector2f> ret;
    for (auto snakepos : snakePosition)
        ret.emplace_back( snakepos->getPosition() );
    return ret;

And, for good measure, you could just apply a transform() on it.
[/edit]
Hope this helps.
Last edited on
o i forgot to initialize sorry. thank you :) transform() ?
Sorry, I was being lazy.

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;
}

Hope this helps.



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
Last edited on
Topic archived. No new replies allowed.