简体   繁体   中英

3D table of constant size

I am asked to create a class that contains a 3D table. However, the size is not standard and are given by the user. I can obviously use a vector, and that would be fine. However, can I make the vector of constant size after initializing it, or is there an alternative to create such an object, without the use of a vector? Thanks in advance

However, can I make the vector of constant size after initializing it

If you don't resize the vector, then its size remains constant. You can make the vector a private member of a class to enforce such restriction with a class invariant.

or is there an alternative to create such an object, without the use of a vector?

You can allocate a dynamic array without using a vector. But it won't be quite as convenient.

You can by using new , but it means a lot of work on your side. Here is a minimal example:

class threeDTable {
  public :
    threeDTable(int n){data = new yourType[n*n*n]; size=n;}
    ~threeDTable(){delete []data;}
    void set(int x, int y, int z, yourType value){data[size*size*x + size*y + z]=value;}
    yourType get(int x, int y, int z)const {return data[size*size*x + size*y + z];}
  private :
    yourType *data;
    int size;
  };

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM