LoginSignup
2
2

More than 5 years have passed since last update.

wxArrayを使う

Last updated at Posted at 2013-01-03

wxWidgetsで遊んでいてwxArrayを使うサンプルがぱっと見無かったのでメモ

  • 使用環境
    • wxWidgets 2.8.11
    • Mac OSX 10.4.11/ppc
wxarraytest.cpp
#include <wx/wx.h>
#include <stdio.h>

class MyData;
WX_DEFINE_ARRAY(MyData *, ArrayOfMyData);

class MyData
{
public:
  int x;
  int y;
  MyData(int, int);
  void Print();
};

MyData::MyData(int inx, int iny) {
  x = inx; y = iny;
}

void MyData::Print() {
  wxPrintf(_("%d, %d\n"), x, y);
}

int main(int argc, char ** argv) {
  ArrayOfMyData array;
  array.Alloc(20);
  // Add to array
  for ( int i = 0; i < 30 ; i++ )
    array.Add(new MyData(i, -i));
  // Remove some items
  for ( int i = 29 ; i > 0 ; i -= 2) {
    MyData* item = array[i];
    wxPrintf(_("Remove %d at %p\n"), i, item);
    delete item;
    array.RemoveAt(i);
  }

  // Show array's items
  for ( size_t i = 0 ; i < array.GetCount() ; i++ )
    array[i]->Print();

  // Finalize
  for ( size_t i = 0 ; i < array.GetCount() ; i++ ) {
    delete array[i]; array.RemoveAt(i);
  }
  return 0;
}

実行結果はこんなかんじ:

Remove 29 at 0x1308390
Remove 27 at 0x1308370
Remove 25 at 0x1308350
Remove 23 at 0x1308330
Remove 21 at 0x1308310
Remove 19 at 0x1308270
Remove 17 at 0x1308250
Remove 15 at 0x1308230
Remove 13 at 0x1308210
Remove 11 at 0x13081f0
Remove 9 at 0x13081d0
Remove 7 at 0x13081b0
Remove 5 at 0x1308190
Remove 3 at 0x1308170
Remove 1 at 0x1308150
0, 0
2, -2
4, -4
6, -6
8, -8
10, -10
12, -12
14, -14
16, -16
18, -18
20, -20
22, -22
24, -24
26, -26
28, -28
Hello?

int型整数のタプルを格納するクラスMyDataを定義して、そのクラスへのポインタの配列ArrayOfMyDataを定義。クラスへのポインタの配列はwxArrayじゃなくてwxObjArray使えって書いてあった気がする。

普通の配列みたいに扱えてなかなか便利。
最初にarray.Alloc(20)してその後30個の要素を追加しているのであらかじめallocした数以上の要素を利用できる。

2
2
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
2
2