I have an algorithm which expects a std::vector
(call it A
). However, I already have B
with N + 2
entries and what I basically want is to pass B.data() + 2
, so the algorithm gets the last N
entries from B
. If A
is modified, then so is B
.
When using double*
pointers it's perfectly clear how I should make it, but is this also possible with std::vector
s? I mean, the nice thing with a vector is that it handles the memory for me, and what I want now is to forbid it (if B
or A
get destroyed, they should leave the pointed data untouched).
Like this:
std::vector< double > B({1,2,3,4,5});
std::vector< double > A(B.data() + 2, B.size() - 2);
// A and B share data now. A is 3, 4, 5
I know that the algorithm could be designed better for this purpose by taking a pair of iterators, but that's not in my hands.
UPDATE
(In the comments, one wished to see the signature, here it is)
nlopt::result nlopt::opt::optimize(std::vector<double> &x, double &opt_f);
However, my original intention was to be very clever and let the algorithm optimize direclty in my vector B
, so what I ended up with was something like this:
std::vector< double > B(N + 2);
// do something with it here, like put initial values
std::vector< double > A( B.begin() + 2, B.end() );
optimize( A );
std::copy(A.begin(), A.end(), B.begin() + 2);
I really don't worry about this workaround, I also read in the documentation of nlopt
that the vectors are copies internally anyway a number of times if one uses the C++ interface instead of the C one.
But again, this example really opened my eyes regarding algorithm interface design and that it's worth to invest some time browsing through e.g. the boost libraries like range
and so on.