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++ 中创建矩阵的正确方法
基础教程推荐
- 为 C/C++ 中的项目的 makefile 生成依赖项 2022-01-01
- 如何在不破坏 vtbl 的情况下做相当于 memset(this, ...) 的操作? 2022-01-01
- 在 C++ 中循环遍历所有 Lua 全局变量 2021-01-01
- 如何“在 Finder 中显示"或“在资源管理器中显 2021-01-01
- Windows Media Foundation 录制音频 2021-01-01
- 为什么语句不能出现在命名空间范围内? 2021-01-01
- 使用从字符串中提取的参数调用函数 2022-01-01
- 从 std::cin 读取密码 2021-01-01
- 如何使图像调整大小以在 Qt 中缩放? 2021-01-01
- 管理共享内存应该分配多少内存?(助推) 2022-12-07