Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to pass a stl vector to a function which takes a const [] (c++)

i have a 3d stl vector,

vector<vector<vector<double> > > mdata;

i also have a function

myfun(const double ya[]);

to be more precise, it's 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' dimension of data to myfun. i've been trying 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 apprecitated!

like image 602
andreas-h Avatar asked Dec 05 '25 17:12

andreas-h


1 Answers

You could 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]);
}

The elements of vector are stored contiguously. So this way is standard as I hope :)

23.2.4 Class template vector

1 A vector is a kind of sequence that supports random access iterators. In addition, it supports (amortized) constant time insert and erase operations at the end; insert and erase in the middle take linear time. Storage management is handled automatically, though hints can be given to improve efficiency. The elements of a vector are stored contiguously, meaning that if v 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().
like image 63
Khaled Alshaya Avatar answered Dec 08 '25 11:12

Khaled Alshaya



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!