【问题标题】:C++ Builder how to build dynamic Objects with vector?C++ Builder如何用向量构建动态对象?
【发布时间】:2016-01-11 18:37:10
【问题描述】:

我正在 C++ Builder 中开发 IOS 应用程序。我的问题是如何在 for 循环中构建 TImages。我公开声明了向量:

#include <vector>

std::vector<TImage*> Image(c); // public declaration 

void __fastcall TForm1::Button2Click(TObject *Sender)
{
 for (int i = 0; i < c ; i++){

    c = 5 // c should be send to te array
    Image[i] = new TImage(this); // I tried it this way but when i click the button i get an acess violence error
    Image[i]->Parent = BoardItem ;
    Image[i]->Height = 20 ; 
    Image[i]->Width = 20 ; 
   }
}

那么如何使用向量在 for 循环中创建图像?

Dynamic alocation an array of Images in C++ Builder 我查找了该问题的最后一个答案,但没有描述如何循环执行。

【问题讨论】:

  • 当你做std::vector&lt;TImage*&gt; Image(c);c的值是多少?
  • 感谢您的回答,但我的问题已经解决了:)
  • 请将您得到的答案作为答案,以帮助他人。
  • @JesseWatZ 我的帮助不足以勾勒出来吗?
  • 当我评论时我没有意识到你做了一个。

标签: c++ arrays image dynamic vector


【解决方案1】:

// c should be send to te array

如果你改变变量c的值,它不会改变数组的大小。

您必须在Image 向量上调用resize() 来更改大小,但这并不适合。最好写类似

void TForm1::ClearImage() {
 for (int i = 0; i < Image.size(); ++i) {
     delete Image[i];
 }
 Image.clear();
}

void __fastcall TForm1::Button2Click(TObject *Sender)
{
 ClearImage();
 c=5;
 for (int i = 0; i < c ; i++){

    Image.push_back(new TImage(this));
    Image.back()->Parent = BoardItem ;
    Image.back()->Height = 20 ; 
    Image.back()->Width = 20 ; 
   }
}

【讨论】:

  • 我如何命名图像?他们不能有相同的名字吗?不都叫Image吗?
  • 虽然也是我的第一个,但他已经创建了一个包含 5 个默认构造元素的向量。
  • 多亏了这一切都很好,但还剩下一个问题。当我在上面的循环中删除图像时,为什么我必须 Image.clear() ?
  • @Philip1895 您删除了之前使用new 创建的对象。需要clear() 来重置vector
  • 好的,谢谢,但我不需要在销毁表单上也清除它吗?
猜你喜欢
  • 2021-08-05
  • 1970-01-01
  • 2019-04-15
  • 2014-05-31
  • 2015-11-05
  • 1970-01-01
  • 2014-06-03
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多