KingAzaiez
KingAzaiez

Reputation: 113

For auto loop to fill a matrix

I want to transform a adjacency list to adjacency matrix

The adjacency list is as follows:

vector< vector< Arc * > * > _adjacences;

and class arc has these:

public:
    int sommetArrive; // tops
    int longueur; // distance

I have 3 vectors as follows to be filled:

std::vector <int> list[_adjacences.size()]; // vector of tops
std::vector <int> >listD[_adjacences.size()]; // vector of distances
std::vector < vector <int> > matrix( _adjacences.size(), 
         vector<int>(_adjacences.size(),0 )); // matrix init to 0 and to be filled to become adjacenecy matrix

I filled the vectors this way:

for (unsigned i = 0; i < _adjacences.size(); i++){
    for (auto j : *_adjacences[i]){
         list[i].push_back(j->sommetArrive);
         listD[i].push_back(j->longueur);
    }
}

Now my issue is here: I try to make the adjacency matrix, I was able to make it

0 0 0 0 1 0 1 
0 1 0 1 0 1 0
....

by doing this :

for (unsigned i = 0; i < _adjacences.size(); i++) {
    for (auto j : list[i]){
          matrix[i][j] = 1;
    }
}

I want to make the adjacency matrix with distances between the tops instead of 1.

I tried making it this way:

for (unsigned i = 0; i < _adjacences.size(); i++) {
    for (auto j : list[i]){
         for (auto k : listD[i]){ // MY ERROR IS SOMEWHERE HERE 
              matrix[i][j] = k;   // IN THIS LOOP
         }
     }
}

I end up with the same distance in the same row

0  0  0  0  35  0  35
0 22  0  22  0  22 0

How can i fix my loop ?

Upvotes: 0

Views: 159

Answers (1)

john
john

Reputation: 87959

So I think list and listD are a mistake because you are separating information that should stay together. Instead you should construct matrix directly from _adjacences. Like this

vector< vector< Arc * > * > _adjacences = ...;

std::vector<vector<int>> matrix(_adjacences.size(), vector<int>(_adjacences.size()));
for (unsigned i = 0; i < _adjacences.size(); i++) {
    for (auto j : *_adjacences[i]) {
         matrix[i][j->sommetArrive] = j->longueur;
    }
}

If you want list and listD as well as matrix then you can populate those in the same way that you are now.

Upvotes: 1

Related Questions