Correct way to create a vector of ofxGui objects

I’m a bit confused because of the syntax to create an ofParameter,

ofParameter<float> vec0;

is somewhat at odds with the way vectors are created

vector<float> starting_position;

I’m sure there is a simple explanation, and I promise I looked around quite a bit and couldn’t find what I was looking for. The goal is to manipulate 10 floats with sliders, but I would prefer to do this in a procedural way rather than having float0, float1, float2 and so on.

My silly way of doing this so far is

// ofApp.h

ofxPanel gui;
ofParameterGroup sliderGroup;
ofParameter<float> vec0;
ofParameter<float> vec1;
ofParameter<float> vec2;
ofParameter<float> vec3;
ofParameter<float> vec4;
ofParameter<float> vec5;
ofParameter<float> vec6;
ofParameter<float> vec7;
ofParameter<float> vec8;
ofParameter<float> vec9;
// ofApp.cpp 

    sliderGroup.setName("sliders");
    sliderGroup.add(vec0.set("vec 0", 0, -5, 5));
    sliderGroup.add(vec1.set("vec 1", 0, -5, 5));
    sliderGroup.add(vec2.set("vec 2", 0, -5, 5));
    sliderGroup.add(vec3.set("vec 3", 0, -5, 5));
    sliderGroup.add(vec4.set("vec 4", 0, -5, 5));
    sliderGroup.add(vec5.set("vec 5", 0, -5, 5));
    sliderGroup.add(vec6.set("vec 6", 0, -5, 5));
    sliderGroup.add(vec7.set("vec 7", 0, -5, 5));
    sliderGroup.add(vec8.set("vec 8", 0, -5, 5));
    sliderGroup.add(vec9.set("vec 9", 0, -5, 5));

gui.setup(sliderGroup);

I simply need each slider to control a separate float variable, and would like to do this .add() business in a for loop, etc.

Tips appreciated, and thank you

Hi @prismspecs,

Hey a std::vector is a container that is used to store instances of a class that are all the same type, and in a contiguous section of memory. So a vector of this type would be:

std::vector<ofParameter<float>>;

And a loop might look something like this:

// in ofApp.h, the vector becomes the class variable:
    ofParameterGroup sliderGroup;
    std::vector<ofParameter<float>> parameters;

// then in ofApp.setup()
    int num = 10;
    float value = 0.0;
    float min = -5.0;
    float max = 5.0;
    for(size_t i{0}; i < num; ++i)
    {
        ofParameter<float> p;
        std::string name = "vec";
        name += to_string(i);
        p.set(name, value, min, max);

        parameters.push_back(p);
        // a copy of p ends up in the vector, but p itself will go out of scope after each interation of the loop;
        // so probably make sure to add the one from the vector to the ofParameterGroup
        sliderGroup.add(parameters.at(i));
    }

This compiles OK for me, but you should test it out to make sure it works the way we think it should.

1 Like

Incredibly helpful and exactly what I needed, thank you!