在c ++中创建矩阵的正确方法 [英] A proper way to create a matrix in c++

查看:1077
本文介绍了在c ++中创建矩阵的正确方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想为图形创建一个邻接矩阵。因为我读了,使用矩阵[x] [y] 的数组是不安全的,因为它们不检查范围,我决定使用矢量模板类的stl。我需要存储在矩阵中的都是布尔值。所以我的问题是,如果使用 std :: vector< std :: vector< bool> *> * 产生太多开销,或者如果有一个更简单的方法矩阵,以及如何正确初始化它。



编辑:非常感谢快速的答案。我只是意识到,那当然我不需要任何指针。矩阵的大小将在开始时初始化,直到程序结束才会更改。这是一个学校项目,所以如果我写好代码,虽然技术上的表现并不重要,但会很好。使用STL很好。使用类似boost,可能不赞赏。

解决方案

请注意,您也可以使用 boost.ublas 以及 boost.graph 以多种方式表示和操纵图形,以及对它们使用算法等。 / p>

编辑:无论如何,为您的目的做一个矢量的范围检查版本不是一件困难的事情:

 模板< typename T> 
class BoundsMatrix
{
std :: vector< T>内_;
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版本,奇怪的使用异常,但你得到的想法。


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.

EDIT: 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];
        }
};

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

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆