Question

I am using IBM CPLEX to model a constraint program using the C++ API.

I have declared a bool var array as so:

IloEnv env;
IloBoolVarArray bVars(env);

Then I add 3 variables to the array and assign them names as so:

bVars.add(IloBoolVar(env,"a"));
bVars.add(IloBoolVar(env,"b"));
bVars.add(IloBoolVar(env,"c"));

My question is:

Do i need to know the index of a variable (0,1 or 2) in this array in order to reference/use the variable in an expression?

I cannot seem to find a way to refer to a variable using the assigned names "a", "b" or "c".

Was it helpful?

Solution

The "name" of the variable in the constructor is used when you do an "exportModel" to a .lp file. It's useful for interactive debugging, but not for accessing in your code and it is not at all required. If you want to use the elements of an array in an expression, then you need to know the index. It's not an associative array. However, you have quite a few other options. You could assign them to c++ variables.

IloBoolVar a(env, "a");
IloBoolVar b(env, "b");
IloBoolVar c(env, "c");

The type IloBoolVar is a handle to implementation so it's also possible to store the values in an array if you also need that.

IloBoolVarArray bVars(env);
bvars.add(a);
bvars.add(b);
bvars.add(c);

In that case bvars[0] and a represent the same variable. You could also use a std::map or a hash-table to store the variables if you needed random-access by name.

OTHER TIPS

You can also define an array like this

IloBoolVarArray bvars( env , 3 );

It will automatically instanciate an array of 3 boolean variable that you can then access by the [] operator as any array.

If your program involves a lot of variable it would be better and easier to use integer index instead of name.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top