The following is a toy example:
An image stores a width, height and filepath, represented by the struct IMAGE:
#include <cstdlib>
#include <type_traits>
struct IMAGE {
int WIDTH;
int HIGHT;
const char* FILEPATH;
};
static_assert(std::is_pod<IMAGE>::value);
There are a 100 unique IMAGEs in a game such as a Dirt Block, a Sword, and a Main Menu etc.
One approach (1) to storing all these 100 images in a program is to use separate variables for each unique image:
int main(){
IMAGE DIRTBLOCK = IMAGE(25, 25, "RESOURCE\\DIRTBLOCKIMAGE");
IMAGE SWORD = IMAGE(100, 25, "RESOURCE\\SWORDIMAGE");
IMAGE MAINMENU = IMAGE(500, 500, "RESOURCE\\MAINMENUIMAGE);
}
Another approach (2) could be to use an enum of Image Names and an array of IMAGEs:
enum IMAGENAME : unsigned char {
DIRTBLOCK,
SWORD,
MAINMENU,
NUMIMAGES
};
IMAGE* IMAGES;
int main(){
IMAGES = (IMAGE*)std::malloc(sizeof(IMAGE) * NUMIMAGES);
IMAGES[DIRTBLOCK] = IMAGE {25, 25, "RESOURCE\\DIRTBLOCKIMAGE"};
IMAGES[SWORD] = IMAGE {100, 25, "RESOURCE\\SWORDIMAGE"};
IMAGES[MAINMENU] = IMAGE {500, 500, "RESOURCE\\MAINMENUIMAGE"};
std::free(IMAGES);
}
Generally, What are the advantages and disadvantages of approaches (1), (2). Alternatively, is there a better approach(3), I have not considered.
I am relatively new to c++, so your help is appreciated.
std::vector<IMAGE>.mallocandfreesimpler than this? Every C++ programmer is familiar withstd::vector. It's one of the first things people learn, along withstd::string. If there is a fixed number ofIMAGEs, you could instead use astd::array, like this.vectoris complicated, but usingvectoris close to brainless. It's like driving a car. Any fool can drive a car, but it's takes some mad skills to build one.high_resolution_clockis just an alias forstready_clockin MSVC.high_resolution_clockshould however not be used. Even its inventor says so. Re: "It is my firm belief you should learn the C way of doing things before the C++ way of doing things" - you'll find that most experienced C++ programmers will disagree with that.