0

I want to find the best solution for a problem. However, the solution(chromosome) is represented as a vector of integers (length unknown).

As far as I know, NLOPT accepts double* as an input. Furthermore, the number of attributes is a constant. So is it possible to wrap around and pass a std::vector<int>?

EDIT - Tiny desciption of the problem:

I have a set of points. I want to sort this point using a heuristic. This heuristic is some what complex. It is the less possible number of crossing lines between them if we draw line between each consecutive points. I was thinking of something close to the gentic algorithm where I can represent the solution as chromosome of the ordered indexes.

I pick NLOPT because I have very successful previous experiment with it. I know it could be solved using many other genetic or bees algorithms libraries. But here I am asking about NLOPT it self.

4

1 回答 1

1

您有 avector<int>作为输入,但您的库采用 adouble*和恒定大小。

你可以做这样的事情:

#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]您可以使用as访问矢量数据double *。它的常量大小dVector.size()保持有效,直到向量不修改其内部存储。

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

编辑

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

Juste include#include <nlopt.hpp>以 C++ 方式调用 nlopt。

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

于 2015-11-10T10:50:36.680 回答