【问题标题】:What data structure is prefered instead of manipulating multiple vectors首选什么数据结构而不是操纵多个向量
【发布时间】:2016-08-22 12:06:28
【问题描述】:

我已经实现了一个对图像进行计算的类。该处理一次对给定图像的子集(假设 1000 个图像中的 100 个)进行,并且每个图像需要不同数量的迭代才能完成。该处理使用 GPU,因此不可能一次使用所有图像。图像处理完成后,将删除该图像并添加另一个图像。所以我使用三个不同的向量image_outcomeimage_indeximage_operation 来保存有关图像的信息:

  1. image_outcome 是一个std::vector<float>,它的每个元素都是一个值,用作决定图像何时完成的标准。
  2. image_index 是一个std::vector<int>,用于保存原始数据集中图像的索引。
  3. image_operation 是一个std::vector<MyEnumValue>,它包含用于更新image_outcome 的操作。属于enum 类型,其值是许多可能的操作之一。

还有两个功能,一个是删除完成的图像,另一个是添加尽可能多的图像(如果输入中还有足够的图像)。

  1. remove_images() 函数采用所有三个矩阵和图像矩阵,并使用std::vector.erase() 删除元素。
  2. add_images() 再次获取三个矩阵,图像矩阵将新图像和相关信息添加到向量中。

因为我在每个具有相同索引的向量上使用了erase()(以及类似的添加方式),所以我想:

  1. 使用具有三个向量(嵌套结构)的私有 struct
  2. 使用使用三个向量(嵌套类)实现的私有class
  3. 使用除 vec 之外的其他数据结构。

下面是代码的高级示例:

class ComputationClass {
  public:
    // the constructor initializes the member variables
    ComputationClass();
    void computation_algorithm(std::vector<cv::Mat> images);

  private:
    // member variables which define the algorithms parameters
    // add_images() and remove_images() functions take more than these
    // arguments, but I only show the relevant here
    add_images(std::vector<float>&, std::vector<int>&, std::vector<MyEnumValue>&);
    remove_images(std::vector<float>&, std::vector<int>&, std::vector<MyEnumValue>&);
};

void ComputationClass::computation_algorithm(std::vector<cv::Mat> images) {
  std::vector<float> image_output; 
  std::vector<int> image_index;
  std::vector<MyEnumValue> image_operation;

  add_images(image_output, image_index, image_operation);

  while (there_are_still_images_to_process) {
    // make computations by updating the image_output vector
    // check which images finished computing
    remove_images(image_output, image_index, image_operation);
    add_images(image_output, image_index, image_operation);
  }
}

【问题讨论】:

  • 包含floatintMyEnumValue 的结构,然后是该结构的向量?
  • 关联在一起的数据应该保持在一起,否则您最终将很难维护它。它也会减少缓存未命中。

标签: c++ vector data-structures stl


【解决方案1】:

我认为,与具有 3 个向量的结构相比,用户定义对象的单个向量会更好。

std::vector<MyImage> images;

class MyImage {
    Image OImage; // the actual image
    float fOutcome;
    int dIndex;
    MyEnumValue eOperation;
    bool getIsDone() {
        return fOutcome > 0; // random condition
    }
}

您可以使用条件添加到向量或从向量中删除

if( (*it).getIsDone() ) {
    VMyVector.erase( it );
} 

在我看来,保持 3 个并行的向量很容易出错,很难修改。

【讨论】:

  • 我建议使用指针,这样会更有效率。 std::vector<:shared_ptr>> images;
  • 3 个向量可能更快。
  • 我是否应该在另一个类中实现这个类,因为它将被包含在另一个项目中并且我想提供最好的封装。
  • @user5438960 我认为您应该在拥有矢量 的相同位置实现此类。如果您想要最好的封装,请将所有变量设为私有,并将修饰符和访问器设为公共。如果您的“最佳封装”意味着更具体的内容,请解释更多。
  • @KrzysztofBargieł 我认为我个人不喜欢不必要的动态分配。 shared_ptr 中的任何内容都将被动态分配,而插入向量中的任何内容都将被动态分配。
猜你喜欢
  • 2015-12-09
  • 1970-01-01
  • 1970-01-01
  • 2014-08-05
  • 2018-04-08
  • 2018-12-04
  • 2018-02-20
  • 2019-11-22
相关资源
最近更新 更多