2015-04-25 41 views
0

我.h文件中附加價值的雙指針

#ifndef ADJACENCYMATRIX_H_ 
#define ADJACENCYMATRIX_H_ 
#include <iostream> 
#include <fstream> 
#include <cstring> 
#include <cstdio> 
#include <cstdlib> 
using namespace std; 



class AdjacencyMatrix{ 

private: 
    int vertexCount; 
    int vertexFirst; 
    int edgeCount; 
    int **wage; 
    int **matrix; 

public: 
    AdjacencyMatrix(); 
    virtual ~AdjacencyMatrix(); 
    bool createFromFile(string path); 
    void viewMatrix(); 



}; 

#endif /* ADJACENCYMATRIX_H_ */ 

我讀形式的文件,我想它寫信給我的初始化矩陣,但它不工作。你可以幫我嗎 ?

#include "AdjacencyMatrix.h" 

AdjacencyMatrix::AdjacencyMatrix() { 
    this->vertexCount=0; 
    this->vertexFirst=-1; 
    this->edgeCount=0;  
} 

AdjacencyMatrix::~AdjacencyMatrix() { } 

bool AdjacencyMatrix::createFromFile(string path) { 
    fstream file; 
    file.open(path.c_str(), fstream::in); 
    if (file.good()) 
    { 
     int vertexF,vertexE,wag; 
     cout << "file opened" << endl; 
     file >> this->edgeCount; 
     file >> this->vertexCount; 
     file >> this->vertexFirst; 

     matrix = new int *[edgeCount]; 
     wage = new int *[edgeCount]; 

     for (int i = 0; i < vertexCount; i++) 
     { 
      matrix[i]=new int[edgeCount]; 
      wage[i]=new int[edgeCount]; 
     } 

     //fill matrix by zeros 
     for (int i = 0; i < vertexCount; i++) 
     { 

      for(int j=0; j<edgeCount;j++) 
      { 
       matrix[i][j]=0; 
       wage[i][j]=0; 
      } 
     } 

     // fill matrix by 1 
     for(int i=0; i<edgeCount; i++) 
     { 
      file >> vertexF >> vertexE >> wag; 
      cout << " w " << wag; 
      matrix[vertexF][vertexE] = 1; 
     } 

     file.close(); 
     return true; 
    } 
    cout << "File does not opened" << endl; 
    return false; 
} 

void AdjacencyMatrix::viewMatrix(){ 
    cout << " Adjacency Matrix "; 
    for(int i=0; i<vertexCount; i++) 
    { 
      for(int j=0; i<edgeCount;i++) { 
       cout << this->matrix[i][j] << " "; 
      } 
      cout<< endl; 
    } 
} 

,這部分不工作(我的意思是,沒有什麼事是顯示器和showMatrix()不工作)。我想從文件中獲得價值,然後將其編寫爲matrix[x][y] = 1,因爲我想創建圖形路徑。

for(int i=0; i<edgeCount; i++) 
{ 
    file >> vertexF >> vertexE >> wag; // cout work in this line 
    matrix[vertexF][vertexE] = 1; // does not work 
} 
+0

您可以將AdjacencyMatrix.h添加到問題中嗎?沒有看到類聲明很難回答這個問題。 – phantom

+0

請發佈[MCVE](http://www.stackoverflow.com/help/mcve)。你是什​​麼意思「不起作用」? – Barry

回答

1

你的矩陣的大小是錯誤的:

matrix = new int *[edgeCount]; // wrong size 
wage = new int *[edgeCount]; // wrong size 

for (int i = 0; i < vertexCount; i++) 
    { 
     matrix[i]=new int[edgeCount]; 
     wage[i]=new int[edgeCount]; 
    } 

當你定義矩陣你應該使用vertexCount代替,就像這樣:

matrix = new int *[vertexCount]; 
wage = new int *[vertexCount]; 

這可能會導致段故障或奇怪的行爲。

而且,當你閱讀由用戶提供的數據,你應該確認他們:

file >> vertexF >> vertexE >> wag; 
matrix[vertexF][vertexE] = 1; 

確定vertexFvertexE並不比vertexCount - 1edgeCount - 1更大?

+0

好的,謝謝;) –