Passing array of vectors as a function parameter (

2019-08-09 16:12发布

问题:

I have an array of vectors in one class:

class MeasurementData
{
private:
    std::vector<double> m_measuredStrengths[3];
}

And I would like a function of another class to examine that and pass back an integer based on the analysis, e.g.

int CStrengthAnalyser::GetBestFit(std::vector<double> measuredStrengths[3])
{
    int bestFit = -1;
    // do stuff
    return bestFit;
}

And I'm a little confused by the best practice for passing this kind of object around, plus setting up my receiving function to guarantee no changes to the original data.

Is my function declaration OK as-is, or do I need to add some best practice tweaks?

回答1:

The function you have right now is the same function as:

int CStrengthAnalyser::GetBestFit(std::vector<double> * measuredStrengths )

So it can definitely modify the vectors. If you're always dealing with an array of size 3 you can take a const reference to an array of size 3.

int CStrengthAnalyser::GetBestFit(std::vector<double> const (&measuredStrengths)[3])

Or if you want to make it more generic:

struct CStrengthAnalyser
{
  // ...

  template<std::size_t N>
  int GetBestFit(std::vector<double> const (&measuredStrengths)[N])
  { ... }
};

In this case the member function definition must appear in the header (or, to be precise, the definition must be visible to the compiler at the callsite).

If you want to avoid the ugly reference to array syntax you could change the MeasurementData definition to contain a std::array<std::vector<double>, 3> instead of a plain C array. Then passing a reference to that is cleaner

int CStrengthAnalyser::GetBestFit(std::array<std::vector<double>, 3> const& measuredStrengths)

And finally, you could also deduce the size of the std::array using a function template as shown previously.



回答2:

I would suggest that you use a vector of vectors here, like

    vector<vector<double> > your_measure(3);

When you pass it into another function, you can use the key word const to it, like

    my_fun(vector<vector<double> > const & your_vec_vec);