Arrays

Hi,

I’m new to OF and trying to simply create an array of rectangles using a class. Does anyone have example code I could look off to get an idea of how to do this?

Thanks

you mean for reading about arrays? http://www.learncpp.com/cpp-tutorial/61-arrays-part-i/

Thanks.

I have a class Button and I just wasn’t sure where to declare the array, for example would buttons[]= new Button;
go in the testApp.mm file?

you can do for example: #define nButtons = 3 in testApp.h and Button buttons[nButtons];

I suggest you to use containers instead of arrays:
http://www.cplusplus.com/reference/vector/vector/

They are more efficient and cleaner to work with.

Regarding your question, you can:
1-Create your class…

2-In the TestApp.h import the class
#include “MyClass.h”

3-Declare the variable with the amount of objects you want to create:
static const unsigned int AMOUNT = 10;

4-Declare the container you want to use. In most cases you will go for a vector.
std::vector mObjects;

5-Create a typedef with the iterator for the container. You will use this to access the methods on your class.
typedef vector::iterator mIter;

6-On the implementation (.mm or .cpp file) iterate with a for loop to instantiate your objects:
for(unsigned int i=0;i<AMOUNT;i++){
mObjects.push_back(myObject());
}

7-Depending how your class is implemented, you can access its methods by using the container’s iterator:
update(){

for(mIter i=mObjects.begin(); i!=mObjects.end();++i){
i->update();
}
}

…do the same with draw or the methods you declared on your class

8-If you are using a lot of elements I would suggest using pointers and smart pointers to have a good memory house keeping.

hope it helps!

Thanks for the example. Is it possible to do this with images?
vector images;
then something like:
images.push_back(ofImage(imagePath));

I’m also assuming I don’t need a separate class for image?

Vectors can be filled with any type (int, float, ObjectX or ObjectY). The important thing is to instantiate them accordingly: vectorX.push_back(ObjectX(x,y,z));

Probably a very stupid question but how do you add images to the vector?
Is it possible to do images[0].loadImage(“1.png”); ?

hm, you can also use a vector with pointers to images

  
vector <ofImage*> Pics;  

create & load with

  
Pics.push_back(new ofImage());  
            Pics.back()->loadImage(path1);  
Pics.push_back(new ofImage());  
            Pics.back()->loadImage(path2);  
Pics.push_back(new ofImage());  
            Pics.back()->loadImage(path3);  

draw them

  
for(int i=0;i<Pics.size();i++) {  
Pics[i]->draw(0, 0);  
}  

this has several advantages & disadvantages…(pointers, passing vale to other classes, boa…)

greetings ascorbin

1 Like

Thank you. It’s compiling without errors but for some reason my images are white squares.

use ofEnableAlphaBlending();