I want to make a filled matrix as an instance variable in my .hpp file but end up with seg fault.
I have a graphe class. In my .cpp file, i filled an adjacency matrix as follows
void Graphe::shortRoute( void ){
std::vector<vector<int>> matrix(_adjacences.size(), vector<int>(_adjacences.size()));
std::vector<vector<int>> shortPath(_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;
}
}
... more and more code to get a filled shortPath matrix.
I implemented Floyd algorithm and everything works perfectly here and I printed the matrix to check it, it's all good.
the resulted matrices matrix and shortPath I wanted to make as instance variables
I tried as follows THIS CAUSES SEG FAULT WHY ?
for ( unsigned i = 0; i < _adjacences.size(); i++)
for (unsigned j = 0; j < _adjacences.size(); j++){
shortPath[i][j] = SP[i][j];
matrix[i][j] = M[i][j];
}
and in my .hpp file I declared SP and M as follows:
class Graphe
{
private:
vector< vector< Arc * > * > _adjacences;
std::vector<vector<int>> M;
std::vector<vector<int>> SP;
....
as soon as I launch the program, i get seg fault from that new addition
Arc is as follows:
class Arc
{
public:
int sommetArrive;
int longueur;
string nom;
Arc( int a_sommetArrive, int a_longueur, string a_nom );
virtual ~Arc( void );
friend ostream & operator <<( ostream &, Arc const & );
};
for ( unsigned i = 0; i < _adjacences.size(); i++) for (unsigned j = 0; j < _adjacences.size(); j++){ shortPath[i][j] = SP[i][j]; matrix[i][j] = M[i][j]; }can be simplified to thisshortPath = SP; matrix = M;You don't have to write loops to copy vectors, the whole vector can be copied in a single assignment. I have a suspicion this might even cure your problem.