0

I am a beginner in c++ and I have worked on vectors just not on 2D vectors. I have surfed a lot, but data on internet is very specific related to 2D vectors. I need to build a graph given an input file and then apply Kruskal's algorithm for minimum spanning tree.

My approach:

A1, A2, A3.....An would be the first row and col of my 2d Vectors and they will
 contain name. I will read the input file and start matching the names.
 And then at graph[i][j] I will put the weight.

     A1 A2 A3......  

A1   w  w  w ....... 
A2   w  w  w .......
A3   w  w  w .......

. . . . Now I am trying something like this:

struct mat{
       string name;
}

int main(){
vector<vector<mat>> matrix;
// In order to insert
vector<mat> tempVec;
tempVec[0].name = "stack";
matrix.push_back(tempVec);
}   

Now I have no idea that when I do tempVec[0].name, 0 indicates which row or col of Matrix. If it indicates row then how do I know which col is being accessed. I mean vector.push_back(tempVec), assigns which position in my Matrix to data. I know I can access individual elements like Matrix[i][j]. But How can I assign weight to a particular row, col position and then access it.

Further do you think will be a good implementation for Kruskal's Method.

Please be simple in your code and explanatory. And thanks in advance.

1 Answers1

0

Using vector<vector<T>> is a fairly suboptimal way to represent matrices, even though it is often used. It would be better to make a one-dimensional vector<T> of size rows x cols. You can then index it as follows (assuming you follow C-style row major ordering):

vector<mat> matrix(rows*cols);
...
element_ij=matrix[i*cols+j];

In your current code, you never insert anything into matrix:

vector<vector<mat>> matrix;
// In order to insert
vector<mat> tempVec;
tempVec[0].name = "stack";
vector.push_back(tempVec);

I assume the last line should be matrix.push_back(tempVec);.

Marc Claesen
  • 16,778
  • 6
  • 27
  • 62
  • I made the change it was supposed to be matrix.push_back.....So do you think now it would represent 2D Matrix. – Likon_Master May 08 '13 at 12:38
  • It certainly is *a* way to represent a 2D matrix. – Marc Claesen May 08 '13 at 12:40
  • So how do I know which row and col is accessed. That is my real Question. – Likon_Master May 08 '13 at 12:42
  • When you would use this kind of setup, it is up to you to define the indexing scheme and stick to it. Typically `matrix[i][j]` refers to row i, column j. If you would simply do `matrix[i]`, you will get a `vector` as a result. It's up to you to choose whether your outermost index refers to columns or rows. – Marc Claesen May 08 '13 at 12:48