A proper way to create a matrix in c++(在 C++ 中创建矩阵的正确方法)
问题描述
我想为图形创建一个邻接矩阵.因为我读到使用 matrix[x][y] 形式的数组是不安全的,因为它们不检查范围,所以我决定使用 stl 的向量模板类.我需要在矩阵中存储的只是布尔值.所以我的问题是,如果使用 std::vector<std::vector<bool>* >* 会产生太多的开销,或者是否有更简单的矩阵方法以及我如何正确初始化它.
I want to create an adjacency matrix for a graph. Since I read it is not safe to use arrays of the form matrix[x][y] because they don't check for range, I decided to use the vector template class of the stl. All I need to store in the matrix are boolean values. So my question is, if using std::vector<std::vector<bool>* >* produces too much overhead or if there is a more simple way for a matrix and how I can properly initialize it.
非常感谢您的快速回答.我刚刚意识到,当然我不需要任何指针.矩阵的大小将在开始时被初始化,直到程序结束才会改变.这是一个学校项目,所以如果我编写漂亮"的代码会很好,尽管技术性能不是太重要.使用 STL 很好.使用诸如 boost 之类的东西可能不受欢迎.
Thanks a lot for the quick answers. I just realized, that of course I don't need any pointers. The size of the matrix will be initialized right in the beginning and won't change until the end of the program. It is for a school project, so it would be good if I write "nice" code, although technically performance isn't too important. Using the STL is fine. Using something like boost, is probably not appreciated.
推荐答案
请注意,您也可以使用 boost.ublas 用于矩阵创建和操作以及 boost.graph 以多种方式表示和操作图形,以及对它们使用算法等.
Note that also you can use boost.ublas for matrix creation and manipulation and also boost.graph to represent and manipulate graphs in a number of ways, as well as using algorithms on them, etc.
编辑:无论如何,为您的目的做一个向量的范围检查版本并不是一件难事:
Edit: Anyway, doing a range-check version of a vector for your purposes is not a hard thing:
template <typename T>
class BoundsMatrix
{
std::vector<T> inner_;
unsigned int dimx_, dimy_;
public:
BoundsMatrix (unsigned int dimx, unsigned int dimy)
: dimx_ (dimx), dimy_ (dimy)
{
inner_.resize (dimx_*dimy_);
}
T& operator()(unsigned int x, unsigned int y)
{
if (x >= dimx_ || y>= dimy_)
throw std::out_of_range("matrix indices out of range"); // ouch
return inner_[dimx_*y + x];
}
};
请注意,您还需要添加运算符和/或迭代器的 const 版本,以及异常的奇怪用法,但您明白了.
Note that you would also need to add the const version of the operators, and/or iterators, and the strange use of exceptions, but you get the idea.
这篇关于在 C++ 中创建矩阵的正确方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:在 C++ 中创建矩阵的正确方法
基础教程推荐
- CString 到 char* 2021-01-01
- 为什么 typeid.name() 使用 GCC 返回奇怪的字符以及如 2022-09-16
- 非静态 const 成员,不能使用默认赋值运算符 2022-10-09
- 初始化列表*参数*评估顺序 2021-01-01
- 为什么 RegOpenKeyEx() 在 Vista 64 位上返回错误代码 2021-01-01
- GDB 显示调用堆栈上函数地址的当前编译二进制文 2022-09-05
- 我应该对 C++ 中的成员变量和函数参数使用相同的名称吗? 2021-01-01
- 如果我为无符号变量分配负值会发生什么? 2022-01-01
- 通过引用传递 C++ 迭代器有什么问题? 2022-01-01
- 为什么派生模板类不能访问基模板类的标识符? 2021-01-01
