2011-07-22 28 views
0

问题是:是否可以使用下面的稀疏列表实现创建稀疏矩阵?在特殊情况下,使用带类模板(SparseList *>)的类模板?如何创建一个稀疏矩阵作为列表的列表? (C++)

我已经创建了一个名为SparseList的类模板,我可以在需要的任何索引中添加元素。

我想用它来创建一个SparseMatrix类模板。所以,我想下面...

//SparseMatrix.h 

template <typename T> 
class SparseMatrix { 
    public: 
     SparseMatrix(); 

    private: 
     SparseList<SparseList<T>*> *matrix; 
}; 

template <typename T> 
SparseMatrix<T>::SparseMatrix() { 
    matrix = new SparseList<SparseList<T>*>(); 
} 

但是当我尝试初始化它的主...

int main() { 
    SparseMatrix<int> *matrix; 
    matrix = new SparseMatrix<int>(); //without this line it compiled normally. 

    return 0; 
} 

我得到了以下错误......

In file included from src/main.cpp: 
SparseMatrix.h: instantiated from 'SparseMatrix<T>::SparseMatrix() [with T = int]' 
main.cpp: instantiated from here 
SparseList.h: error: template argument required for 'struct SparseMatrix' 

我在MinGW中使用NetBeansIDE 6.9.1。

编辑:

//SparseList.h 
template <typename T> 
class SparseList { 

    template <typename U> 
    friend std::ostream & operator<<(std::ostream &output, const SparseList<U> &list); 

public: 
    SparseList(); 
    virtual ~SparseList(); 

    void insert(T &entry, int index); 
    T & get(int i); 
    int length(); 

private: 
    struct ListNode { 
     int index; 
     T *entry; 
     ListNode *next; 
    }; 

    ListNode *head; //pointer to the first entry in the sparse list. 
    int size; //# of entries. 
}; 

我已经测试插件和获取,构造函数和析构函数,一切都在SparseList。工作正常...... =)

+0

不要说“新”没有理由。事实上,不要说'新',期限。另外,为什么你有一个列表清单?对(i,j)的值的映射是否更合适? –

+0

我不明白...你说什么“不要无故说新话”。 那么......从来没有想过这一点。不知道如何使用地图。我会看看这个。谢谢。 =) – Ken

+0

只是不要说新的。你为什么?你可以在主函数中说'SpareMatrix 矩阵'。 –

回答

2

为什么所有的指针?

这应该做的工作是你的类内部数据存储:

std::map<std::pair<I, I>, T> 

哪里I是您的索引类型(例如int)和T是你的号码类型(例如双)。

或者您可以使用compressed_matrixboost::ublas