gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-28 03:48:03 25 4
gpt4 key购买 nike

问题是:是否可以使用以下稀疏列表实现来创建稀疏矩阵?特别是,使用带有类模板(SparseList*>)的类模板?

我创建了一个名为 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>*>();
}

但是当我尝试在 main 上实例化它时......

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'

我将 NetBeansIDE 6.9.1 与 MinGW 结合使用。

编辑:

//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 中的所有内容。工作正常... =)

最佳答案

为什么所有的指针?

这应该可以作为您在类里面的数据存储:

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

I 是您的索引类型(例如 int),T 是您的数字类型(例如 double)。

或者您可以只使用 compressed_matrix来自 boost::ublas

关于c++ - 如何创建一个稀疏矩阵作为列表列表? (C++),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6785022/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com