João Daniel
João Daniel

Reputation: 8986

Copy vectors from constant variables

I'm wrinting a function where I need to respect the following interface:

double logDensity(double x, PDFType type,
                  std::vector<std::vector<double const *> > const &parameters,
                  double const *lower, double const *upper) const;

I need to split that parameters vector into two vectors inside this function:

vector<double> f = (parameters[0]);
vector<double> t = (parameters[1]);

However this code leads me to these errors messages:

DPwexp.cc: In member function 'double pwexponential::DPwexp::logDensity(double, PDFType, const std::vector<std::vector<const double*> >&, const double*, const double*) const':
DPwexp.cc:38:38: error: conversion from 'const std::vector<const double*>' to non-scalar type 'std::vector<double>' requested
 vector<double> f = (parameters[0]);
                                  ^

What is the best way to copy those two vectors to new variables inside my function?

Thanks!

Upvotes: 0

Views: 1084

Answers (2)

Spock77
Spock77

Reputation: 3325

If parameters are passed by const&, the intend was not to change them inside the function. Why you need to copy them? The prototype assumes that you'll work with the parameters' values without changing.

const vector<double const*>& f = (parameters[0]);
const vector<double const*>& t = (parameters[1]);

Upvotes: 1

R Sahu
R Sahu

Reputation: 206667

You can use:

// Create f with the right number of elements.
std::vector<double> f(parameters[0].size());

// Use std::transform to convert pointers to double and
// store them in f.
std::transform(parameters[0].begin(), parameters[0].end(), 
               f.begin(), [](double const* in) { return *in; });

// Similarly for t.
std::vector<double> t(parameters[1].size());
std::transform(parameters[1].begin(), parameters[1].end(), 
               t.begin(), [](double const* in) { return *in; });

Upvotes: 1

Related Questions