c++ - CPLEX C++:避免将变量添加到两个变量数组中
问题描述
我有两个IloNumVarArrays
,叫做p
和p_old
。我想保存当前状态p_old
并向其中添加新变量p
(但只是p
因为p_old
应该是备份)。但是当我向 中添加新变量p
并将它们添加到我的模型时,它们也会被添加到p_old
。我想避免将它们添加p_old
到p_old
. 这是一个例子。
#include <vector>
#include <ilcplex/ilocplex.h>
ILOSTLBEGIN
int main(){
bool solved;
// vector R contains all requests
std::vector <int> R = {0,1,2,3,4,5,6,7,8,9,10};
int new_request;
// use this stringstream to create variable and constraint names
std::stringstream name;
IloEnv env;
IloModel model(env);
IloNumVarArray p(env,R.size());
IloConstraintArray accept(env,R.size());
IloNumVarArray p_old(env, R.size());
for (const auto& i: R)
{
name << "p_" << i;
p[i] = IloNumVar(env, 0, 1, ILOBOOL, name.str().c_str());
name.str("");
p_old[i] = p[i];
}
IloExpr expr(env);
// Create objective function
for (const auto& i : R)
{
expr += p[i];
}
IloObjective obj(env, expr, IloObjective::Minimize);
model.add(obj);
expr.clear();
env.out() << endl << p << endl;
env.out() << endl << p_old << endl;
// Create the solver object
IloCplex cplex(model);
env.out() << "Before" << endl;
env.out() << model << endl;
cplex.exportModel("Before.lp");
solved = cplex.solve();
if (solved)
{
// If CPLEX successfully solved the model, print the results
std::cout << "\n\nCplex success!\n";
std::cout << "\tStatus: " << cplex.getStatus() << "\n";
std::cout << "\tObjective value: " << cplex.getObjValue() << "\n";
// remove p_1 and p_2 from model
p[1].end();
p[2].end();
// add new request to R, create variable p and corresponding constraint
new_request = 11;
R.push_back(new_request);
name << "p_" << new_request;
p.add(IloNumVar(env,0,1,ILOBOOL,name.str().c_str()));
name.str("");
new_request = 12;
R.push_back(new_request);
name << "p_" << new_request;
p.add(IloNumVar(env,0,1,ILOBOOL,name.str().c_str()));
name.str("");
accept.add(2, IloRange());
accept[11] = IloRange(env,1,p[11],1,"accept_11");
accept[12] = IloRange(env,1,p[12],1,"accept_12");
model.add(accept[11]);
model.add(accept[12]);
env.out() << endl << p << endl;
env.out() << endl << p_old << endl;
env.out() << "After" << endl;
env.out() << model << endl;
cplex.exportModel("After.lp");
solved = cplex.solve();
}
expr.end();
env.end();
}
整个事情背后的原因是我有一个更大的拨号问题模型,它接收新请求并在每次新请求到达时解决。当发生这种情况时,将添加与新请求相对应的变量和约束。但是,添加所有这些变量和约束可能需要不超过 10 秒的时间,因为请求必须快速收到答复。如果碰巧在 10 秒后修改模型还没有完成,则请求被拒绝,即不再需要之前添加的所有变量和约束,并且我不想将它们包含在模型中。那就是我需要的地方IloNumVarArray p_old
,因此在超时修改后,我可以使用
p.end_elements();
p.add(p_old.getSize(), IloNumVar());
for (const auto& i: R)
{
p[i] = p_old[i];
}
或类似的东西......有人有什么想法吗?非常感谢您的帮助!
解决方案
推荐阅读
- javascript - 同时调用Javascript函数和django视图函数
- flutter - 如何在 Flutter 中显示来自 Wordpress 的图像
- jquery - 具有自动生成 ID 的动态点击功能
- python - 如果使用不允许的类型调用 add_argument() 是否可能引发错误?
- amazon-s3 - React-admin :一次将多张图片上传到 s3
- azure-cognitive-search - 访问 Azure 认知搜索索引时出现套接字错误
- python - 更改yolov3安装路径 | 简历2
- python - 如何防止django中的多用户登录(注意:当第一个用户登录时,防止第二个用户登录)
- android - “返回 super.getItemId(position)”和只返回“返回位置”有什么区别
- macos - macOS:打印时自动打开应用程序