Originally posted by: SystemAdmin
Paul, you are right, a map would be faster and result in better code. However, you have to be careful in C++. By default a map in C++ uses the "less than" operator to compare two keys. This operator is overloaded for IloNumVar so that
IloNumVar x(env), y(env);
x < y // <- This is of type IloConstraint!
produces a constraint rather than a boolean value. When you try to do
std::map<IloNumVar,int> varmap;
map.insert(std::pair<IloNumVar,int>(x, 1));
you will get an error that IloConstraint cannot be converted to bool. So you either have to provide your own comparator to the map or use the values returned by IloNumVar::getId() or IloNumVar::getImpl() as key in the map (operator "less than" is not overloaded for those).
I think it is simpler to just use id or pointer to implementation as key but for the sake of completeness, here is one way (among many others) to actually use the variables as keys:
#include <map>
#include <iostream>
#include <ilcplex/ilocplex.h>
struct IloNumVarLess {
bool operator()(IloNumVar const& v1, IloNumVar const& v2) const {
return v1.getId() < v2.getId();
}
};
int
main(void)
{
try {
IloEnv env;
IloNumVar x(env);
IloNumVar y(env);
IloModel model(env);
std::map<IloNumVar,int,IloNumVarLess> varmap;
varmap.insert(std::pair<IloNumVar,int>(x, 1));
varmap.insert(std::pair<IloNumVar,int>(y, 2));
model.add(x < y);
} catch (IloException& e) {
std::cerr << "IloException: " << e.getMessage() << std::endl;
return -1;
}
return 0;
}
#CPLEXOptimizers#DecisionOptimization