Search code examples
c++xcodefor-loopvectorsdl

Vectors C++ not working with C++ SDL_Surface


#include<iostream>
#include<string>
#include<vector>

#include<SDL2/SDL.h>
#include<SDL2/SDL_image.h>

const int WIDTH = 800;
const int HEIGHT = 640;

int main()
{
    std::vector<SDL_Surface> *devImages = {};
    SDL_Surface *windowSurface = NULL;
    SDL_Event windowEvent;

    SDL_Init(SDL_INIT_EVERYTHING);

    SDL_Window *window = SDL_CreateWindow("Hello SDL World", SDL_WINDOWPOS_UNDEFINED, SDL_WINDOWPOS_UNDEFINED, WIDTH, HEIGHT, SDL_WINDOW_ALLOW_HIGHDPI);
    windowSurface = SDL_GetWindowSurface(window);

    if(window == NULL){
        std::cout<<"Could not create window: "<<SDL_GetError()<< std::endl;
        return 1;
    }

    if(!(IMG_Init(IMG_INIT_PNG) & IMG_INIT_PNG)){
        std::cout<<"Could not create window: "<<IMG_GetError()<< std::endl;
        return 1;
    }

    SDL_Surface *img1 = IMG_Load("Test.png");
    SDL_Surface *test = IMG_Load("Hi.png");
    SDL_Surface *f = IMG_Load("F.png");

    auto it = *devImages->insert(devImages->begin(), 3);
    devImages->insert(it, 2);

    //      devImages->emplace_back(test);
   //      devImages->emplace_back(f);

   while(true)
   {
       if(SDL_PollEvent(&windowEvent) && SDL_QUIT == windowEvent.type)
           break;

       //SDL_BlitSurface(imageSurface, NULL, windowSurface, NULL);
        for(auto item: *devImages){
            SDL_BlitSurface(&item, NULL, windowSurface, NULL);
        }
         SDL_UpdateWindowSurface(window);
}

//SDL_FreeSurface(imageSurface);
//dimageSurface = NULL;
windowSurface = NULL;

SDL_DestroyWindow(window);
SDL_Quit();

return EXIT_SUCCESS;

}

My code is giving me errors when I try to loop through the Vector. Could anyone tell me how to loop through this vector or what I'm doing wrong. I'm trying to render more than one image on the screen, and I started with Sonar System's SDL Tutorial 4 on GitHub. Thank you.


Solution

  • Pressumably the declaration of the vector of surfaces is off.

    Instead of

    std::vector<SDL_Surface> *devImages = {};
    

    try

    std::vector<SDL_Surface*> devImages = {};
    

    Also when using the vector, instead of

    for(auto item: *devImages){
        SDL_BlitSurface(&item, NULL, windowSurface, NULL);
    }
    

    try

    for(auto item: devImages){
        SDL_BlitSurface(item, NULL, windowSurface, NULL);
    }