传递载体的数组作为函数参数(值不会改变) [英] Passing array of vectors as a function parameter (values will not change)

查看:412
本文介绍了传递载体的数组作为函数参数(值不会改变)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有载体的一类数组:

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.

是我的函数声明OK原样,还是我需要添加一些最佳实践调整?

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

推荐答案

您现在所拥有的功能是一样的。

The function you have right now is the same as

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

所以它绝对可以修改矢量秒。如果你总是使用尺寸为3的数组处理,您可以乘坐常量参考尺寸为3的数组。

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])
  { ... }
};

在这种情况下,该成员函数定义必须出现在报头(或成为precise,定义必须为调用点,编译器可见)。

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).

如果你想避免丑陋的引用数组语法,你可以修改 MeasurementData 定义包含的std ::阵列&LT;的std ::矢量&lt;双&gt;中3 GT; ,而不是一个普通的C数组。然后使一个参考是清洁器

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)

最后,你也可以推断出使用函数模板的std ::阵列的大小,如图previously。

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

这篇关于传递载体的数组作为函数参数(值不会改变)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆