【VS/CPLEX】C++用cplex解线性规划问题举例

问题:

Maximize x1 + 2x2 + 3x3
subject to
–x1 + x2 + x 3 20
x
1 3x2 + x 3 30
with these bounds
0 x1 40
0
x2 infinity
0
x3 infinity


环境:vs2010 cplex2012

代码:

头文件:

#pragma once
#include
#include "Util.h"//只是包含iostream 和std
class MyCplex
{
private:
	IloEnv env;

	IloModel model;
	IloCplex cplex;

	IloObjective objective;
	IloNumVarArray vars;
	IloRangeArray constraints;

public:
	MyCplex();
	void test();
	~MyCplex();
};

源文件

#include "MyCplex.h"



MyCplex::MyCplex()
{
	model = IloModel(env, "myCplex");
	vars = IloNumVarArray(env);
	constraints = IloRangeArray(env);
}


MyCplex::~MyCplex()
{
	env.end();
}

void MyCplex::test()
{
	objective = IloAdd(model, IloMaximize(env));

	/*By column*/

	constraints.add(IloRange(env, 0, 20, "constraint_1"));
	constraints.add(IloRange(env, 0, 30, "constraint_2"));

	model.add(constraints);

	IloNumArray parameters(env, 2);
	parameters[0] = -1;
	parameters[1] = 1;
	vars.add(IloNumVar(objective(1) + constraints(parameters), 0, 40,ILOFLOAT, "var_1"));

	vars.add(IloNumVar(objective(2) + constraints[0](1)+constraints[1](-3), 0, IloInfinity, ILOFLOAT, "var_2"));

	vars.add(IloNumVar(objective(3) + constraints[0](1)+constraints[1](1), 0, IloInfinity, ILOFLOAT, "var_3"));

	model.add(vars);

	cplex = IloCplex(model);
	cplex.solve();

	cplex.out() << "solution status:" << cplex.getStatus() << endl;
	cplex.out() << "objective value:" << cplex.getObjValue() << endl;

	cplex.exportModel("model.lp");

}
写一个main就可以执行了。
在项目目录下面可以找到一个写了详细model的文件。

你可能感兴趣的:(visual,studio,ilcplex)