data structures – A proper way to create a matrix in c++

data structures – A proper way to create a matrix in c++

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_;

        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.

Best way:

Make your own matrix class, that way you control every last aspect of it, including range checking.

eg. If you like the [x][y] notation, do this:

class my_matrix {
  std::vector<std::vector<bool> >m;
  my_matrix(unsigned int x, unsigned int y) {
    m.resize(x, std::vector<bool>(y,false));
  class matrix_row {
    std::vector<bool>& row;
    matrix_row(std::vector<bool>& r) : row(r) {
    bool& operator[](unsigned int y) {
  matrix_row& operator[](unsigned int x) {
    return matrix_row(;
// Example usage
my_matrix mm(100,100);
mm[10][10] = true;

nb. If you program like this then C++ is just as safe as all those other safe languages.

data structures – A proper way to create a matrix in c++

The standard vector does NOT do range checking by default.

i.e. The operator[] does not do a range check.

The method at() is similar to [] but does do a range check.
It will throw an exception on out of range.


Other notes:
Why a vector<Pointers> ?
You can quite easily have a vector<Object>. Now there is no need to worry about memory management (i.e. leaks).

std::vector<std::vector<bool> >   m;

Note: vector<bool> is overloaded and not very efficient (i.e. this structure was optimized for size not speed) (It is something that is now recognized as probably a mistake by the standards committee).

If you know the size of the matrix at compile time you could use std::bitset?

std::vector<std::bitset<5> >    m;

or if it is runtime defined use boost::dynamic_bitset

std::vector<boost::dynamic_bitset>  m;

All of the above will allow you to do:

m[6][3] = true;

Leave a Reply

Your email address will not be published.