A proper way to create a matrix in c++

后端 未结 10 2364
無奈伤痛
無奈伤痛 2020-11-27 05:33

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 deci

10条回答
  •  谎友^
    谎友^ (楼主)
    2020-11-27 06:37

    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 
    class BoundsMatrix
    {
            std::vector 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];
            }
    };
    

    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.

提交回复
热议问题