next up previous
Next: About this document ... Up: Plain matrices in C++ Previous: Dynamically allocated matrices

Matrices with the Standard C++ library vector class

We can also use the vector class to build a matrix. These matrices cannot be passed as arguments to Fortran-encoded subroutines, however.



#include <iostream>
#include <vector>
using namespace std;

typedef vector<double> Vec;
typedef vector<Vec> Mat;

Vec operator*(const Mat &a, const Vec &x){
  int i,j;
  int m = a.size();
  int n = x.size();

  Vec prod(m);

  for(i = 0; i < m; i++){
    prod[i] = 0.;
    for(j = 0; j < n; j++)
      prod[i] += a[i][j]*x[j];
  }
  return prod;
}

int main(){
  int i,j,m,n;

  cout << "Enter the number of rows in the matrix \n";
  cin >> m;
  cout << "Enter the number of columns in the matrix \n";
  cin >> n;

  // Allocate space for the vectors
  Vec row(n);
  Mat a;

  cout << "Enter the matrix\n";
  for(i = 0; i < m; i++){
    for(j = 0; j < n; j++)cin >> row[j];
    a.push_back(row);
  }

  cout << "Enter the vector\n";
  Vec x(n);
  for(j = 0; j < n; j++)
    cin >> x[j];

  Vec b = a*x;

  cout << "\nA*x = \n";
  for(i = 0; i < m; i++)
    cout << b[i] << "\n";
}

Here are the notable features.




typedef vector<double> Vec;
typedef vector<Vec> Mat;

We are using templates and typdefs to make Vec be the name of a vector class with vector components made from doubles. And we are defining Mat to be a vector the components of which are themselves doube-precision vectors. That is to say, we are treating the matrix as a list of its row vectors, and we think of the list as a kind of generalized vector. The vector class is general enough, it is even possible for the row vectors to have varying length, but we would probably not call them matrices in that case.




  Vec row(n);

We are using a constructor that takes a size argument. If we initialize the vector length in this way, we can then assign individual elements directly, as in cin >> row[j], rather than with push_back. Of course, we can still add more elements beyond the initial n with push_back, if we like.




Vec operator*(Mat &a, Vec &x){

This definition overloads the multiplication operator so we can multiply a vector by a matrix with the expression

  b = a*x;


next up previous
Next: About this document ... Up: Plain matrices in C++ Previous: Dynamically allocated matrices
Carleton DeTar 2012-10-22