在 C++ 中创建矩阵的正确方法

2021-12-18 00:00:00 matrix data-structures graph c++ stl

我想为图形创建一个邻接矩阵.因为我读到使用 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.

相关文章