How to pass a vector to a stl function that takes const [] (C ++)
I have a 3d stl vector,
vector<vector<vector<double> > > mdata;
i also has the function
myfun(const double ya[]);
more precisely, it is a function from the GNU Scientific Library,
gsl_spline_init(gsl_spline * spline, const double xa[], const double ya[], size_t size);
but this is not related to my problem.
so now I want to pass the "last" data dimension to myfun. i tried this:
for (int s = 0; s < msize; s++) {
accelerators = new gsl_interp_accel*[msize];
splines = new gsl_spline*[msize];
for (int i = 0; i < msize; i++) {
accelerators[i] = gsl_interp_accel_alloc();
splines[i] = gsl_spline_alloc(gsl_interp_cspline_periodic, msize+1);
gsl_spline_init(splines[i], &(*mgrid.begin()), &(*mdata[s][i].begin()), msize+1);
}
}
But the compiler (g ++, 64bit, Ubuntu) complains:
In member function
std::vector<std::vector<std::vector<double, std::allocator<double> >, std::allocator<std::vector<double, std::allocator<double> > > >, std::allocator<std::vector<std::vector<double, std::allocator<double> >, std::allocator<std::vector<double, std::allocator<double> > > > > > SimpleAmfCalculator::interp_m(int)
: Calculator.cpp: 100: error: cannot convert 'std::vector<double, std::allocator<double> >*
to'const double*
for argument '3 to'int gsl_spline_init(gsl_spline*, const double*, const double*, size_t)
make: *** [Calculator.o] Error 1
Any help is greatly appreciated!
source to share
You can pass the address of the first element, for example:
#include <vector>
void fun(const double data[])
{
}
int main()
{
std::vector<std::vector<std::vector<double> > > data3d;
....
fun(&data3d[0][0][0]);
}
Items vector
are kept contiguous. So this is the standard way I hope :)
23.2.4 Class template vector
1 Vector is a kind of sequence that supports random access iterators. In addition, it supports (amortized) persistent time insertion and end-of-end erase operations; insert and erase in the middle of linear time. Storage management is handled automatically, although hints may be for efficiency.
elements of a vector are stored
adjacent , which means that ifv
is a vector, where T is some type other than bool, then it obeys the identity:
&v[n] == &v[0] + n for
all 0 <= n < v.size().
source to share
This screams for a general solution.
template<typename T, typename A>
T* PointerOf(std::vector<T,A> & vec)
{
return &vec.at(0);
}
template<typename T, typename A>
const T* ConstPointerOf(const std::vector<T,A> & vec)
{
return &vec.at(0);
}
myfun(ConstPointerOf(mdata[s][i]));
Edit: I added a template parameter for the vector allocator as suggested in the comments; I also used in () instead of [], so I wouldn't have to check for an empty vector, and I added a second version of the function for a const pointer.
source to share