我想在求解后从使用 C++ API 创建的 Cplex 模型中删除变量,再次求解并在每次求解后查询求解。
为此,我使用了 cplex.getValues()
。
在下面我修改了 ilolpex1.cpp 示例(也用于 this question 的答案)
随 Cplex 一起提供。
我收到错误“分段错误:11”。
#include <ilcplex/ilocplex.h>
ILOSTLBEGIN
static void
populatebyrow(IloModel model, IloNumVarArray var, IloRangeArray con);
int main (int argc, char **argv)
{
IloEnv env;
try {
IloModel model(env);
IloNumVarArray var(env);
IloRangeArray con(env);
populatebyrow (model, var, con);
IloCplex cplex(model);
cplex.exportModel("lpex1.1.lp");
// Optimize the problem and obtain solution.
if ( !cplex.solve() ) {
env.error() << "Failed to optimize LP" << endl;
throw(-1);
}
env.out() << "Solution status = " << cplex.getStatus() << endl;
env.out() << "Solution value = " << cplex.getObjValue() << endl;
IloNumArray x_sol(env);
cplex.getValues(x_sol,var);
// Delete one of the variables and solve again
var[0].end();
cplex.exportModel("lpex1.2.lp");
// Optimize the problem and obtain solution.
if ( !cplex.solve() ) {
env.error() << "Failed to optimize LP" << endl;
throw(-1);
}
env.out() << "Solution status = " << cplex.getStatus() << endl;
env.out() << "Solution value = " << cplex.getObjValue() << endl;
cplex.getValues(x_sol,var);
}
catch (IloException& e) {
cerr << "Concert exception caught: " << e << endl;
}
catch (...) {
cerr << "Unknown exception caught" << endl;
}
env.end();
return 0;
} // END main
// To populate by row, we first create the variables, and then use them to
// create the range constraints and objective.
static void
populatebyrow (IloModel model, IloNumVarArray x, IloRangeArray c)
{
IloEnv env = model.getEnv();
x.add(IloNumVar(env, 0.0, 40.0));
x.add(IloNumVar(env));
x.add(IloNumVar(env));
model.add(IloMaximize(env, x[0] + 2 * x[1] + 3 * x[2]));
c.add( - x[0] + x[1] + x[2] <= 20);
c.add( x[0] - 3 * x[1] + x[2] <= 30);
x[0].setName("x1");
x[1].setName("x2");
x[2].setName("x3");
c[0].setName("c1");
c[1].setName("c2");
model.add(c);
} // END populatebyrow