c++ - 我可以在 nlopt 中表示染色体吗?

标签 c++ nlopt

我想找到问题的最佳解决方案。但是,解决方案(染色体)表示为整数 vector (长度未知)。

据我所知,NLOPT接受double*作为输入。此外,属性的数量是 constant .那么是否有可能环绕并传递 std::vector<int>

编辑 - 问题的微小描述:

我有一组点。我想使用启发式对这一点进行排序。这种启发式有些复杂。如果我们在每个连续的点之间画线,它们之间交叉线的数量可能会更少。我在想一些接近 gentic 算法的东西,我可以在其中将解决方案表示为有序索引的染色体。

我选择 NLOPT 是因为我之前用它做过非常成功的实验。我知道它可以使用许多其他遗传或蜜蜂算法库来解决。但在这里我问的是 NLOPT it self。

最佳答案

你有一个 vector<int>作为输入,但您的图书馆需要 double*和一个恒定的大小。

你可以这样做:

#include <iostream>
#include <vector>
#include <algorithm>

int main()
{

  std::vector<int> iVector = {1, 2, 3, 4};
  std::vector<double> dVector;

  dVector.resize(iVector.size());

  std::transform(iVector.begin(), iVector.end(), dVector.begin(), [&] (auto i) -> double { return static_cast<double>(i); } );

  for (auto d : dVector)
  {
      std::cout << d << std::endl;
  }

  std::cout << &dVector[0] << std::endl;

}

您可以使用 &dVector[0] 访问 vector 数据作为 double * . dVector.size() 的常量大小它一直有效,直到 vector 不修改其内部存储。

您肯定需要将数据转换回,您可以使用相同的原理来完成。

编辑

否则,有一个直接包装 C API 的 NLopt C++ 引用,因此您可以直接传递 vector<double> .

仅包括 #include <nlopt.hpp>以 C++ 方式调用 nlopt。

参见:http://ab-initio.mit.edu/wiki/index.php/NLopt_C-plus-plus_Reference

关于c++ - 我可以在 nlopt 中表示染色体吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33626775/

相关文章:

c# - 传递运算符和其他参数

python - NLopt 无效参数

c++ - 如何为 C++ 项目创建文档?

c++ - 如何为已明确定义其比较函数的集合定义迭代器?

r - 无法在R 3.3.0上安装nloptr软件包

armadillo - NLopt 与 Armadillo 数据

c - 使用 NLOPT SLSQP(基于梯度的算法)时 C 中的 NLopt nullptr 异常

r - 将参数传递给 r 中的 nloptr

c++ - 使用指令的行为

c++ - 如何生成 C++ 动态对象名称?