I wan to these each classes to myObject class array

Hi, All.

I wan to these each classes(a,b,c) to myObject class array.
So, I want to enter member using for loop.

How can?


#include "ofApp.h"
// Image class
class myObject {
public:
    float width;
    int id;
    string filename;
    ofImage img;
};

// ofSort boolean
bool sortMe(myObject & a, myObject & b){
    if (a.width < b.width){
        return true;
    } else {
        return false;
    }
}

myObject a;
myObject b;
myObject c;

//--------------------------------------------------------------
void ofApp::setup(){
    // enter
    a.id = 0;
    b.id = 1;
    c.id = 2;
    a.filename= "/Users/mun/Desktop/aa.png";
    b.filename= "/Users/mun/Desktop/ants.png";
    c.filename= "/Users/mun/Desktop/lena512.png";
    
    a.img.load(a.filename);
    b.img.load(b.filename);
    c.img.load(c.filename);
    
    a.width = a.img.getWidth();
    b.width = b.img.getWidth();
    c.width = c.img.getWidth();
    
    vector < myObject > objects =  {a,b,c};
    
    // before
    ofLog() << "pre sort" << endl;
    for (int i = 0; i < objects.size(); i++){
        ofLog() << objects[i].id << " " << objects[i].width << endl;
    }
    
    ofSort(objects, sortMe);
    
    // after
    ofLog() << "post sort" << endl;
    for (int i = 0; i < objects.size(); i++){
        ofLog() << objects[i].id << " " << objects[i].width << endl;
        image= objects[i].img;
    }
    
    kk=0;
}

Thanks.
Best,

Hi,
first, please, each time that you post code, select it all and then press the </> button, so it gets auto formated and it becomes easier to read and to copy.

When you call

vector < myObject > objects =  {a,b,c};

each object will be copied instead of making a reference to it.
So, you could either make a pointers vector like

vector < myObject * > objects =  {&a,&b,&c};

or simply create the vector in first place and the just set each element.

vector < myObject > objects;
objects.resize(3);

objects[0].img.load(a.filename);// apply the same logic to access all the other objects.

btw, you can make a function in your class to both set the filename and load the image, it would be a lot cleaner and less bug prone.
cheers

1 Like

Thank you, @roymacdonald.

T’ll try that, and report result~

“I’m human, human is free” - Zorba, The Greek, Khazan Chaquis.