Reputation: 47
I am using Ilog Cplex with Visual C++ 2015 to solve my complex problem. How can I delete all constraints? the following code does not work.
#include <ilconcert/ilomodel.h>
void deleteConstraints(IloModel m)
{
IloModel::Iterator iter(model);
while (iter.ok()) {
if ((*iter).asConstraint().getImpl()) {
(*iter).asConstraint().end();
}
++iter;
}
}
Upvotes: 0
Views: 285
Reputation: 5950
Not every element a model iterator finds is a constraint. The iterator will also produce variables, for example. Using (*iter).isConstraint()
you can test whether it actually points to a constraint. Moreover, it is probably not a good idea to modify the model while iterating over it. So it is probably better to collect all constraints first and then delete them:
IloConstraintArray cons(model.getEnv());
for (IloModel::Iterator it(model); it.ok(); ++it) {
if ( (*iter).isConstraint() )
cons.add((*iter).asConstraint());
}
model.remove(cons);
cons.endElements();
cons.end();
Depending on how you create your model, it may be easier to just keep track of all your constraints while creating them.
Note that you could also use an instance of IloIterator to iterate over all constraints that you created. If any constraint you create is committed to the model then using IloIterator
may be more convenient to find all constraints.
Upvotes: 1