Operator[][] overload

前端 未结 18 1838
轮回少年
轮回少年 2020-11-22 05:46

Is it possible to overload [] operator twice? To allow, something like this: function[3][3](like in a two dimensional array).

If it is pos

18条回答
  •  伪装坚强ぢ
    2020-11-22 06:42

    vector< vector< T > > or T** is required only when you have rows of variable length and way too inefficient in terms of memory usage/allocations if you require rectangular array consider doing some math instead! see at() method:

    template class array2d {
    
    protected:
        std::vector< T > _dataStore;
        size_t _sx;
    
    public:
        array2d(size_t sx, size_t sy = 1): _sx(sx), _dataStore(sx*sy) {}
        T& at( size_t x, size_t y ) { return _dataStore[ x+y*sx]; }
        const T& at( size_t x, size_t y ) const { return _dataStore[ x+y*sx]; }
        const T& get( size_t x, size_t y ) const { return at(x,y); }
        void set( size_t x, size_t y, const T& newValue ) { at(x,y) = newValue; }
    };
    

提交回复
热议问题