Declare Variable(s) During Runtime

I am using an OpenGL wrapper called: "SFML" and there is a class that exists to load images from a particular file location:

1
2
sf::Image myImg;//Create new "Image" instance
if (! myImg.LoadFromFile( "myImg.bmp" ) ) EXIT_FAILURE;


The previous code snippet would be the process to follow for each image that I would like to load. What I would like to do instead is create my own function that would perform my previous example code based on parameters:

 
LoadImg( <Name of Instance>, <Location of Image> );


This way, I can do something similar:
1
2
3
LoadImg("imgBall","gfx/ball.bmp");
LoadImg("imgHat","gfx/hat.bmp");
LoadImg("imgEnemy","gfx/enemy.bmp");
What is your question?
How I would write the "LoadImg" function to provide my needs.
Couldn't you just put their function into yours?
Then when your function is called it will perform theirs.... something like:

1
2
3
4
5
LoadImg(...) {

   sf::Image myImg;//Create new "Image" instance
   if (! myImg.LoadFromFile( "myImg.bmp" ) ) EXIT_FAILURE;
}


along those lines.
Yes, I could however.... I would like to declare the "Image" instance with a specific name (which depends on the argument of my "LoadImg" function.

I'm trying to do something like the following:
1
2
3
4
5
LoadImg( string InstanceName, string ImageFile )
{
    sf::Image InstanceName;
    if (! InstanceName.LoadFromFile( ImageFile ) EXIT_FAILURE;
}


I'm guessing that my code is invalid.
if I understand, you want to create a new variable:
1
2
3
//some code
LoadImg("MyImg","file.bmp");
//now you can use MyImg as it is a variable 

This is not possible but you can use pointers or standard containers:
1
2
3
4
5
6
7
8
#include <map>
#include <string>
std::map<std::string,sf::Image> Images;

LoadImg( std::string Name, std::string File )
{
    Images[Name].LoadFromFile( File );
}
so that
1
2
3
//some code
LoadImg("MyImg","file.bmp");
//now you can use Images["MyImg"] as you want 
Thank you very much. I was thinking about using pointers or simple arrays.

The only problem with arrays is that it would be very difficult to manage once I have an enormous database of images.

I haven't really learned about map and I am glad that you have suggested it as a solution.

If you want to learn more about maps take a look of this http://www.cplusplus.com/reference/stl/map/
(you can see if other containers could be best for you than maps http://www.cplusplus.com/reference/stl/ )
Topic archived. No new replies allowed.