class vector, matrix 2D

How is a 2d matrix created from the vector class? help please.
I need to know how I can have access to read the matrix and cout.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
#include <iostream>
#include <stdlib.h>
#include <vector>
using namespace std;
int main(){
vector<vector<int> > matrix;
vector<int> temp;
int r,c;
cout<<"rows: ";cin>>r;
cout<<"cols: ";cin>>c;
for(int x=0;x<r;x++){
for(int y=0;y<c;y++){temp.push_back(rand()%10);
cout<<matrix[x][y];
}cout<<endl; matrix.push_back(temp);}

return 0;
the best way is

vector<double> matrix(numrows*numcols);
access via
matrix[numcols*desiredrow+desiredcol];

then you can just do a single loop to load it:
for(dx = 0; dx < numrows*numcols; dx++)
matrix[dx] = rand()%10; // approach allows simple iteration, one of many advantages to a 1-d construct).

I think your problem is that temp is not being cleared after each loop iteration, which is probably causing all sorts of problems? Also your {} notation is more confusing than usual. Whitespace costs nothing unless you are printing a physical book.
Last edited on
Topic archived. No new replies allowed.