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.
A matrix is a rectangular array of numbers or symbols arranged in rows and columns. There are different types of matrices like row matrix, column matrix, horizontal matrix, vertical matrix, square matrix, diagonal matrix, identity matrix, equal matrix, singular matrix, etc.
#include<stdio.h> int main(){ int a[3][3],i,j; for(i=0;i<3;i++) for(j=0;j<3;j++){ printf("Enter Element at %d%d position",i+1,j+1); scanf("%d",&a[i][j]); } for(i=0;i<3;i++){ for(j=0;j<3;j++){ printf(" %d ",a[i][j]); } printf("\n"); } return 0; }
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]; } };
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With