【问题标题】:c++: Dynamic array of my own classc++:我自己的类的动态数组
【发布时间】:2018-11-28 09:58:25
【问题描述】:

我已经阅读了一些关于更改数组大小的帖子,但我没有找到适合自己的类的内容。我需要的是一个动态的“区域”数组。

第一步(定义类):

class Region{
private:
    int start;
    int end;
public:
   Region(){
   start=0;
   end=0;
   }
   // some get and set functions
}

第二步(定义一个空的区域数组):

Region regions[0];

第三步(添加新区域)

// Pseudo-Code
generate a help array with dimension 1 (start is 0)
add old regions values to help (none, because it was empty in the beginning)
add the new region to help
delete the regions array
initilize a regions array with dimension 1 (old dimension+1)
copy help to region
delete help

我认为第 2 步已经不正确。我想获得有关第 2 步和第 3 步的帮助。

另外一个好处(在我理解了第 2 步和第 3 步之后)可能是:如何删除特定的索引区域。

问候马丁

【问题讨论】:

  • c++ 中的动态数组被称为std::vector

标签: c++ arrays class dynamic resize


【解决方案1】:

对于动态数组,您正在寻找std::vector<Region>(参见cppreference 的参考资料)。这包含插入、删除和推送操作。

您可以使用 new[]delete[] 自己模拟该行为,但在 C++ 中不建议这样做

【讨论】:

  • 实际上,要模拟std::vector 的行为(至少使用标准分配器),您还需要placement new 参与其中。哪个 OP 可能不想自己做,除非他读了一些关于 C++ 的好书。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-01-09
  • 1970-01-01
  • 2012-06-19
  • 2018-09-11
  • 1970-01-01
相关资源
最近更新 更多