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 
}
4

1 に答える 1

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;

はとよりも大きくありませんvertexFか?vertexEvertexCount - 1edgeCount - 1

于 2015-04-25T19:43:16.310 に答える