本文介绍了一种在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.

推荐答案

请注意,您也可以使用用于矩阵创建和操作,还可以以多种方式表示和操作图表,以及使用对它们的算法等。

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 0; // 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 ++中创建矩阵的正确方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!