7

クラスに次のVertex構造体があります。Graph

struct Vertex
{
    string country;
    string city;
    double lon;
    double lat;
    vector<edge> *adj;

    Vertex(string country, string city, double lon, double lat)
    {
        this->country = country;
        this->city = city;
        this->lon = lon;
        this->lat = lat;
        this->adj = new vector<edge>();
    }
};

私が書いたメソッドを呼び出すとgetCost()、同じ未処理の例外が発生し続けます

アクセス違反読み取り場所 0x00000048

理由がわかりません。

メソッドgetCost():

void Graph::getCost(string from, string to)
{

    Vertex *f = (findvertex(from));
    vector<edge> *v = f->adj;     // Here is where it gives the error
    vector<edge>::iterator itr = v->begin();

    for (; itr != v->end(); itr++)
    {
        if (((*itr).dest)->city == to)
            cout << "\nCost:-" << (*itr).cost;
    }
}

メソッドfindvertex()は type の値を返しますVertex*。このエラーが表示され続けるのはなぜですか?

findVertex メソッド:

Vertex* Graph::findvertex(string s)
{
    vmap::iterator itr = map1.begin();
    while (itr != map1.end())
    {
        if (itr->first == s){

            return itr->second;
        }
        itr++;
    }
    return NULL;
}

map1が定義されている場所:

typedef map< string, Vertex *, less<string> > vmap;
vmap map1;
4

2 に答える 2

2
Vertex *f=(findvertex(from));
if(!f) {
    cerr << "vertex not found" << endl;
    exit(1) // or return;
}

頂点が見つからない場合にfindVertex戻る可能性があるためです。NULL

そうでなければ、これf->adj;はやろうとしています

NULL->adj;

これはアクセス違反を引き起こします。

于 2013-04-14T02:20:03.117 に答える