How do I use a map to store SDL2 Textures in c++?

  c++, sdl-2, sdl-image, stl

So my header file reads:

#include <iostream>
#include <cmath>
#include <map>
#include <SDL2/SDL.h>
#include <SDL2/SDL_ttf.h>
#include <SDL2/SDL_image.h>

using namespace std;

class Screen
{
public:
    const static int WIDTH = 800, HEIGHT = 600;

private:
    SDL_Window *window;
    SDL_Renderer *renderer;
    map<string, SDL_Texture*> textures

    SDL_Rect background;

public:
    Screen(): window(nullptr), renderer(nullptr)
    {
        background.w = WIDTH, background.h = HEIGHT;
        background.x = 0, background.y = 0;
    }
...

When I initialize the texture I use a surface that I get from a picture.

#include "screen.h"

void Screen::loadWaterfall()
{
    SDL_Surface *waterfall = IMG_Load("waterfall.jpg");

    textures["background"] = SDL_CreateTextureFromSurface(renderer, waterfall);

    SDL_FreeSurface(waterfall);
}

How I’m copying the texture to my renderer:

void Screen::render()
{
    SDL_RenderClear(renderer);
    SDL_RenderCopy(renderer, textures["background"], NULL, &background);
    SDL_RenderPresent(renderer);
}

At this point the screen loads to blackness, if I replace the texture to a regularly made one, such as doing:

SDL_Texture *texture = SDL_CreateTextureFromSurface(renderer, waterfall);

... // skip to render function

SDL_RenderCopy(renderer, texture, NULL, &background);

it works fine, as expected. What do you think is going wrong here? I’m thinking it must be something with the fact the texture I make doesn’t use a regular name or something. Not sure.

One more issue is that the screen crashes when I try to destroy the textures in the map as well.

void close()
{
    // close textures
    for(map<string, SDL_Texture*>::iterator it = textures.begin(); it != textures.end(); it++)
        SDL_DestroyTexture(it->second);
....
}

Source: Windows Questions C++

LEAVE A COMMENT