2
votes

I have started with an example of gsl fitting examples and tried to change the arrays to vectors. but when I compile my code, it leads to an error of this, which I dont understand and dont know what is wrong with my code, i appreciate any comment in advance:

example1.cpp:19:73: error: cannot convert ‘std::vector’ to ‘const double*’ for argument ‘1’ to ‘int gsl_fit_linear(const double*, size_t, const double*, size_t, size_t, double*, double*, double*, double*, double*, double*)’ gsl_fit_linear (x, 1, y, 1, n, &c0, &c1, &cov00, &cov01, &cov11, &sumsq);

and this is the code:

#include <iostream>
#include <vector>
#include <gsl/gsl_fit.h>

using namespace std;
int main (void)
{
    int n = 5;
    vector <double> x(5,0);
    vector <double> y(5,0);
    for(int i=0 ; i< 5; i++)
        x[i] = i*3.2; 

    for(int i=0 ; i< 5; i++)
        x[i] = i*2-11.6; 

    double c0, c1, cov00, cov01, cov11, sumsq;

    gsl_fit_linear (x, 1, y, 1, n, &c0, &c1, &cov00, &cov01, &cov11, &sumsq);

  return 0;
}
2

2 Answers

2
votes

I would like to add that c++11 introduced the member function vector::data() that returns the raw pointer of the vector. What are the advantages of vector::data() over @king_nak method ?

1) Clarity. This is subjective, but I think it is more elegant to use

 (...)
 gsl_fit_linear (x.data(), 1, y.data(), 1, n, &c0, &c1, &cov00, &cov01, &cov11, &sumsq);
 (...) 

2) const-correctness. vector::data() has an overload function that returns the const pointer when the function only needs to read the data

3) Empty containers. This answer also cites the fact that it is ok to use vector::data even when the vector is empty. (it is not ok to send an empty container to gsl, but in general this is an extra good feature)

1
votes

The function gsl_fit_linear does not take a vector as input, but a const double *. You have to convert your vector to an array.

As vectors guarantee to store their elements in a continuous memory region (just as arrays), you can use a vector's data like an array. Just get a pointer to its first element:

double *xAsArray = &x.front();

BEWARE: If you change your vector (add/remove elements), the pointer will most probabely get invalid!

You should call your function like this:

sl_fit_linear (&x.front(), 1, &y.front(), 1, n, &c0, &c1, &cov00, &cov01, &cov11, &sumsq);