?

Log in

一个Matrix的模版,主要为了下标访问的语义

原先的Chart Parsing实现是参照NLTK作的,最近由于想出了一套更一般化的用于和其他模块结合,所以需要对数据结构做一下改进。首先想到的是CKY算法中的结构。为了避免动用庞大的Boost库,所以先实现了一个矩阵。主要目的还是为了解析算法的方便,接口和语义大家是否认同就不重要了。

/**
 * Copyright (C)2008 George Ang (gnap.an AT gmail.com)
 * This program is free software; you can redistribute it and/or
 * modify it under the terms of the GNU General Public License
 * as published by the Free Software Foundation; either
 * version 2 of the License, or (at your option) any later version.

 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.

 * You should have received a copy of the GNU General Public License
 * along with this program; if not, write to the Free Software
 * Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
 */

#ifndef GMATRIX_H
#define GMATRIX_H

#include <vector>

template <typename _T>
class GMatrix
{
    public:
        GMatrix( size_t rows, size_t columns )
            : _rows( rows ), _columns( columns ), _storage( rows*columns, _T() )
        {

        }

        GMatrix( size_t rows, size_t columns, _T value )
            : _rows( rows ), _columns( columns ), _storage( rows*columns, value )
        {

        }
        ~GMatrix()
        {
            _storage.clear();
        }

        struct Row
        {
            Row( GMatrix& matrix, size_t row )
                : _matrix( matrix ), _row( row )
            {}

            GMatrix& _matrix;
            size_t _row;
            _T& operator [] ( size_t y )
            {
                return  _matrix._storage[ _row* _matrix.columns() + y ];
            }
        };

        Row operator [] ( size_t x )
        {
            return Row( *this, x );
        }

        size_t columns() { return _columns; }
        size_t rows() { return _rows; }

    protected:
        size_t _rows;
        size_t _columns;
        std::vector<_T> _storage;
};

#endif // GMATRIX_H

Comments