I've got a homework to write an iterative solver(L-BFGS) which needs to save 10 vectors. And update with the latest vector while remove the oldest. I'm using gsl_vector for all other computations, thus I would like to save them directly.
Using vector and vector.push_back and vector.erase was my first thought. But I find it difficult to use it because gsl_vector objects are declared by pointers. If I push_back the pointer, I still have to keep the pointer variable which has no difference with I manually manage the 10 saved variables.
It is appreciated if you could provide some directions on how to managed such.
A short example code:
vector<gsl_vector*> storage(10);
gsl_vector* v = gsl_vector_alloc(100);
gsl_vector_set_zero(v);
storage.push_back(v);
if (storage.size()>10){
storage.erase(storage.begin());
}
gsl_vector_set_all(v, 1); //Could be any other computation
storage.push_back(v);
if (storage.size()>10){
storage.erase(storage.begin());
}
What I want is to save the two different gsl_vector into std::vector. However, due to the fact gsl_vector is an pointer, eventually I have a vector of the same pointer thus no value is stored. If I create 10 pointer objects, then the std::vector became useless, I will be still managing the storage by the 10 pointer variables.
I do not understand why you need to keep the pointer variable, the gsl_vector
is heap allocated, and you do not need to keep a pointer to it outside the std::vector
to keep it alive. What I would suggest is to use a smart pointer with custom deleter, to avoid leaking resources:
#include <vector>
#include <memory>
#include <gsl/gsl_vector.h>
struct gls_vector_deleter {
void operator()(gsl_vector* v) {
gsl_vector_free(v);
}
};
int main()
{
using gsl_vector_ptr = std::unique_ptr<gsl_vector, gls_vector_deleter>;
std::vector<gsl_vector_ptr> storage(10);
gsl_vector_ptr v{ gsl_vector_alloc(100) };
gsl_vector_set_zero(v.get());
storage.push_back(std::move(v));
if (storage.size() > 10) {
storage.erase(storage.begin());
}
//can't use v anymore, lost ownership, use the one stored in vector or a new one
gsl_vector_ptr v2{ gsl_vector_alloc(100) };
gsl_vector_set_all(v2.get(), 1);
storage.push_back(std::move(v2));
if (storage.size() > 10) {
storage.erase(storage.begin());
}
}