简体   繁体   English

如何创建稀疏矩阵作为列表列表? (C++)

[英]How can I create a sparse matrix as a list of lists? (C++)

The question is: Is it possible to create a sparse matrix using the following sparse list implementation?问题是:是否可以使用以下稀疏列表实现来创建稀疏矩阵? In special, using a class template with a class template (SparseList*>)?特别是,使用 class 模板和 class 模板 (SparseList*>)?

I've created a class template named SparseList where I can add elements in whatever index I want.我创建了一个名为 SparseList 的 class 模板,我可以在其中添加任何我想要的索引中的元素。

I'd like to use it to create a SparseMatrix class template.我想用它来创建一个 SparseMatrix class 模板。 So I tried the following...所以我尝试了以下...

//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>*>();
}

But when I try to instantiate it on main...但是当我尝试在 main 上实例化它时...

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

    return 0;
}

I got the following error...我收到以下错误...

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'

I'm using NetBeansIDE 6.9.1 with MinGW.我将 NetBeansIDE 6.9.1 与 MinGW 一起使用。

EDIT:编辑:

//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.
};

I already tested inserts and gets, constructors and destructors, everything in the SparseList.我已经测试了插入和获取、构造函数和析构函数,以及 SparseList 中的所有内容。 Working fine... =)工作正常... =)

Why all the pointers?为什么所有的指针?

This should do the job as your data storage inside your class:这应该作为 class 中的数据存储来完成工作:

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

Where I is your index type (eg int ) and T is your number type (eg double).其中I是您的索引类型(例如int ), T是您的数字类型(例如 double )。

Or you could just use compressed_matrix from boost::ublas .或者你可以只使用boost::ublas中的compressed_matrix矩阵。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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