2

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".

dhrumeel
  • 574
  • 1
  • 6
  • 15

2 Answers2

2

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.

David Nehme
  • 21,379
  • 8
  • 78
  • 117
  • I should mention i am trying to avoid using a map for the names to save space. However, if you don't think there is a better way out, I might have to ahead and use the map. – dhrumeel Feb 16 '12 at 22:23
0

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.

Faylixe
  • 478
  • 6
  • 12