繁体   English   中英

对向量还是向量对?

[英]Vector of pairs or pair of vectors?

在我的代码中,我正在处理一组度量(浮点向量),其中每个元素都有两个关联的不确定性(例如+ up / down)。 假设我想在屏幕上转储这些值,例如

Loop over the vector of the measurements
{
   cout << i-th central value << " +" << i-th up uncertainty << " / -" << i-th down uncertainty << end; 
}

最有效/最优雅的方法是什么?

1)使用一对向量

vector<float> central; //central measurement
pair<vector<float>, vector<float>> errors; //errors
for( int i = 0; i < central.size ; i++ )
{
    cout << central.at(i) << " +" << errors.first.at(i) << " / -" << errors.second.at(i) << endl;
}

2)使用向量对:

vector<float> central; //central measurement
vector<pair<float,float>> errors; //errors
for( int i = 0; i < central.size ; i++ )
{
    cout << central.at(i) << " +" << errors.at(i).first << " / -" << errors.at(i).second << endl;
}

3)两个单独的向量:

vector<float> central; //central measurement
vector<float> errUp; //errors up
vector<float> errDown; //errors down
for( int i = 0; i < central.size ; i++ )
{
    cout << central.at(i) << " +" << errUp.at(i) << " / -" << errDown.at(i) << endl;
}

这个:

其中每个元素都有两个相关的不确定性(例如+ up / down)

对我说,您有一个包含三个元素(值+上/下)的对象。 这样,我将创建该对象并将其存储在单个向量中。

使用多个向量进行存储意味着您必须保持它们同步(以事务方式添加到两者等)。 这充其量是麻烦的,为了安全起见,您必须封装这些向量。

三元向量怎么样?

#include <array>
#include <vector>

using Measurement = std::array<float, 3>;

std::vector<Measurement> data;

我将为单个职责创建一个称为Measurement的类或结构。 您可能不需要两个值来确定不确定性。 在大多数情况下,无论符号如何,它们都是相同的,这意味着一个不确定性值可能就很好。

struct Measurement
{
  union
  {
    float values[3];
    struct { float value, uncertaintyUp, uncertaintyDown; };
  };
}

使用联合将为您提供所需的可读性,以及[]运算符的灵活性。

main()
{
  Measurement x;
  x.value = 1.0f;
  x.uncertaintyUp = 0.1f;
  x.uncertaintyDown = -0.1f;

  for(int i = 0; i < 3; i++)
  {
    cout << x.values[i] << " ";
  }
}

从这里开始,使用Measurement结构的向量将很简单。 如果您可以使用一个容器存储数据,那将是最好的选择。 如果您考虑一下,所有三个向量中的所有数据在时间和容量上都将始终相同,则无需额外的开销; 一个向量可以节省时空。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM