最近我一直在学习如何用c ++编写优化程序。建立优化模型后,我一直收到相同的消息:
有人可以帮我还是告诉我那里发生了什么?非常感谢。
#include <ilcplex/ilocplex.h> ILOSTLBEGIN
typedef IloArray<IloNumVarArray> IloNumVarArray2;
int main(int argc, char ∗∗argv) {
IloEnv env;
try {
const char;
IloInt i, j;
IloModel mod(env);
IloNumVarArray2 x(env);
for (i = 0; i < 3; i++) {
x.add(IloNumVarArray(env, 2, 0.0, IloInfinity));
}
mod.add(IloMaximize(
env, 6.5 * x[0][0] + 11 * x[0][1] + 9.75 * x[1][0] + 12.25 * x[1][1] +
9.5 * x[1][2] + 4.75 * x[2][0] + 7.75 * x[2][1] +
8.5 * x[2][2] + 7.5 * x[3][0] + 8.5 * x[3][1]));
mod.add(x[0][0] + x[1][0] + x[2][0] + x[3][0] >= 500);
mod.add(x[0][1] + x[1][1] + x[2][1] + x[3][1] >= 600);
mod.add(x[0][2] + x[1][2] + x[2][2] + x[3][2] >= 500);
mod.add(x[0][0] + x[0][1] <= 600);
mod.add(x[1][0] + x[1][1] + x[1][2] <= 500);
mod.add(x[2][0] + x[2][1] + x[2][2] <= 300);
mod.add(x[3][0] + x[3][1] <= 400);
IloCplex cplex(mod);
if (!cplex.solve()) {
env.error() << "Failed to optimize LP." << endl;
throw(-1);
}
IloNumArray vals(env);
env.out() << "Solution status = " << cplex.getStatus() << endl;
env.out() << "Solution value = " << cplex.getObjValue() << endl;
env.out() << "Values = " << vals << endl;
} catch (IloException &e) {
cerr << "Error 2" << e << endl;
} catch (...) {
cerr << "Error 1" << endl;
}
env.end();
return 0;
}
就像建议的评论中的人一样,请使用调试器来跟踪问题。更好的是:在调试模式下编译程序。 IloCplex代码在头文件中包含大量断言,可以捕获常见错误。在调试模式下运行代码会导致断言失败:
X& IloArray::operator[] (IloInt i) : Out of bounds operation: index superior to size of array
segfault2.bin++: concert/include/ilconcert/iloenv.h:2246: X& IloArray<X>::operator[](IloInt) [with X = IloNumVarArray; IloInt = long int]: Assertion `(i < _impl->getSize()) || (std:: cerr << "X& IloArray::operator[] (IloInt i) : Out of bounds operation: index superior to size of array" << std:: endl, ilo_stop_assert())' failed.
Aborted
这清楚地表明您正在访问数组之外的数组(就像已经有评论提到的那样)。追溯到此,您可以看到代码中有问题的行是:
mod.add(IloMaximize(
env, 6.5 * x[0][0] + 11 * x[0][1] + 9.75 * x[1][0] + 12.25 * x[1][1] +
9.5 * x[1][2] + 4.75 * x[2][0] + 7.75 * x[2][1] +
8.5 * x[2][2] + 7.5 * x[3][0] + 8.5 * x[3][1]));
您正在访问x[3][*]
,尽管x
数组只有3个元素。因此,只有索引0、1、2对该数组有效。此外,尽管数组的第二维只有2,但是您在某些地方正在访问x[*][2]
。