我的矢量奇怪的值

时间:2014-05-09 09:29:13

标签: c++ pointers vector sdl

我有一种方法可以在我的矢量上添加一些内容,但没有问题。之后我想在程序的另一部分重用我的矢量上的内容,但问题是值不是很好。但我不知道我在哪里错过了什么

以下是代码的一部分

我做这些事情的课程

class MapGenerator
{

public:
    void fillBoard(string level);
    void renderBoard();
    void initTileset();
    MapGenerator();
    ~MapGenerator();
    vector<Tile*> getTiles();

private:
    char     **board;
    int w;
    int h;
    int tileW;
    int tileH;
    vector<Tile*> tiles;

};

这是在initTileset上我把一些东西放在我的瓷砖矢量上。

在我的程序的另一部分之后我打电话给renderBoard()并且有问题,我的矢量上已经有了很多元素,但值不是很好......

这是方法,也许我的itterate方法不正确:

我把内容放在载体上

void MapGenerator::initTileset()
{
    XMLDocument doc;
    doc.LoadFile("ressources/xml/tiles.xml");
    XMLElement* first = doc.FirstChildElement();

    for (XMLElement* child = first->FirstChildElement("tile"); child != NULL; child = child->NextSiblingElement())
    {
      string texture = child->FirstChildElement( "texture")->GetText();
      int x =  atoi(child->FirstChildElement("x")->GetText());
      int y =  atoi(child->FirstChildElement("y")->GetText());
      int w =  atoi(child->FirstChildElement("w")->GetText());
      int h =  atoi(child->FirstChildElement("h")->GetText());
      bool solid = false;
      if (atoi(child->FirstChildElement("solid")->GetText() ) == 1)
        solid =true; 
      char id = child->FirstChildElement("id")->GetText()[0];
      cout << "ID " << id << endl; 
      cout << "create tile : w " << w << " h " << h << endl;
      Tile tile(texture.c_str(), x, y, w, h, solid, id);
      cout << "Tile ID " << tile.getId()<< endl; 

      this->tiles.push_back(&tile);
    }
      cout << tiles.size() << endl;
     // renderBoard();
}

我尝试重用我的载体

void MapGenerator::renderBoard()
{   
    SDL_Rect rect;
    for (int i = 0; i < h; i++)
    {
        for (int j = 0;j < w; j++)
        {
            vector<Tile *>::iterator it;
            for(it = tiles.begin(); it != tiles.end(); ++it) {
                cout <<  " ID :"  << (*it)->getId()  << " h " <<(*it)->getRect().h << " w " << (*it)->getRect().w << endl; 
                if ((*it)->getId() == board[i][j])
                {
                    rect.x = 32 * j;
                    rect.y = 32 * i;
                    rect.h = 32;
                    rect.w = 32;
                    SDL_RenderCopy( GameEngine::getInstance().getRenderer(), (*it)->getTexture(), NULL, &rect );
                     cout << " copy something y = " << i * 32<< " x = " << j *32<< " h " <<(*it)->getRect().h << " w " << (*it)->getRect().w <<endl;
                }
             }
        }
        cout << endl;
    }
}

所以有人有想法吗?

1 个答案:

答案 0 :(得分:4)

当您存储指向向量中的局部变量的指针时,您有undefined behavior。一旦for函数中的initTileset循环迭代,tile变量超出范围并被破坏。

您需要在堆上分配它:

Tile* tile = new Tile(texture.c_str(), x, y, w, h, solid, id);

您当然不应忘记在MapGenerator析构函数中释放已分配的内存。