delorie.com/archives/browse.cgi   search  
Mail Archives: djgpp/1998/04/22/11:30:20

To: djgpp AT delorie DOT com
Subject: Re: PLEASE help with vectors!
References: <353d29bc DOT 235411 AT news DOT ziplink DOT net>
From: M DOT A DOT Bukin AT inp DOT nsk DOT su
Date: 22 Apr 1998 22:18:42 +0700
In-Reply-To: dmt@bigfoot.com's message of "Tue, 21 Apr 1998 23:23:26 GMT"
Message-ID: <20vhs1x4tp.fsf@Sky.inp.nsk.su>
Lines: 70

dmt AT bigfoot DOT com (Jeff W./DMT) writes:

> data members each of another struct type.  I need a 2D array that can
> change size on the fly, i.e. maybe one minute I need a 2x2 array, and
> then 4 minutes later I need a 7x2 array, and then a 500x24 array.  I

  I don't know anything about vectors in STL, but
maybe this simple class will give you some ideas:

---
class vector
{
public:
  vector (void)
  {
    width = 10;
    height = 10;
    data = new int[width * height];
  }
  ~vector (void)
  {
    delete[] data;
  }

  int resize (const int _width, const int _height)
  {
    if ((_width <= 0) || (_height <= 0))
      return -1;
    width = _width;
    height = _height;
    delete[] data;
    data = new int[width * height];
    return 0;
  }

  int* operator[] (const int _y)
  {
    /* FIXME: test for index out of range.  */
    return &data[_y * width];
  }

private:
  int width;
  int height;
  int* data;
  /* Add one more variable to keep size of data
   * and reuse data (don't use delete[]/new[]) if requested
   * size in 'resize' is less or equal to currently used size.
   * In long run it may give a little speedup, but will waste
   * more space than necessary (also helps with fragmentation?).  */
};

int
main (void)
{
  vector v;
  int i;

  v[1][2] = 3;
  if (v.resize (1024, 512) != 0)
    {
      /* Do something.  */
    }
  /* First index can be in [0-1023], second in [0-511].  */
  v[123][456] = 789;
  i = v[324][435];

  return 0;
}
---

- Raw text -


  webmaster     delorie software   privacy  
  Copyright © 2019   by DJ Delorie     Updated Jul 2019