2012-04-23 3 views
0

イテレータを使用してマップ内のデータにアクセスするのに問題があります。イテレータを使用して、マップに挿入されたすべての値を返したいとします。しかし、イテレータを使用すると、それが過去にあったクラスのインスタンス内のメンバを認識しません。クラスのイテレータとポインタを使用したSTLマップ

int main() 
{ 
    ifstream inputFile; 
    int numberOfVertices; 
    char filename[30]; 
    string tmp; 

    //the class the holds the graph 
    map<string, MapVertex*> mapGraph; 

    //input the filename 
    cout << "Input the filename of the graph: "; 
    cin >> filename; 
    inputFile.open(filename); 

    if (inputFile.good()) 
    { 
     inputFile >> numberOfVertices; 
     inputFile.ignore(); 

     for (int count = 0; count < numberOfVertices; count++) 
     { 
      getline(inputFile, tmp); 
      cout << "COUNT: " << count << " VALUE: " << tmp << endl; 

      MapVertex tmpVert; 
      tmpVert.setText(tmp); 
      mapGraph[tmp]=&tmpVert; 
     } 

     string a; 
     string connectTo[2]; 

     while (!inputFile.eof()) 
     { 

      //connectTo[0] and connectTo[1] are two strings that are behaving as keys 

      MapVertex* pointTo; 
      pointTo = mapGraph[connectTo[0]]; 
      pointTo->addNeighbor(mapGraph[connectTo[1]]); 
      //map.find(connectTo[0]).addNeighbor(map.find(connectTo[1])); 
      //cout << connectTo[0] << "," << connectTo[1] << endl; 
     } 

     map<string,MapVertex*>::iterator it; 
     for (it=mapGraph.begin(); it!=mapGraph.end(); it++) 
     { 
      cout << it->getText() << endl; 

     } 
    } 

    return 0; 
} 

コンパイラ出力:

\lab12\main.cpp||In function `int main()':| 
\lab12\main.cpp|69|error: 'struct std::pair<const std::string, MapVertex*>' 
          has no member named 'getText'| 
||=== Build finished: 1 errors, 0 warnings ===| 

その中にあるデータを返すのgetText(と呼ばれる私のMapVertexクラスのアクセス部材)があります。

答えて

4

コンパイラエラーを修正するには、*iteratorpair<string, MapVertex*>であるため、it->second->getText()を実行する必要があります。しかし、あなたのコードには他にも問題があります。マップに挿入するときに、ローカル変数のアドレスをそのマップに挿入します。 forループを使用してマップを反復しようとするまでにこのアドレスは無効になります。私はstd::map<string, MyVertex>として地図を宣言し、地図に挿入するときにコピーMyVertexのがマップに挿入されるようにすることをお勧めします。

+0

私は間違いなく何が起こっているかを見ています。ありがとう! – Arzeimuth

2

tmpVertが問題です。見て、それをスタックに作成します。それは各forループの最後に破壊されます。

It Is Destroyed。

したがって、mapGraphには存在しないオブジェクトへのポインタが保持されています。

+0

おそらく私は私のポインタを使用して不器用だった。それを指摘してくれてありがとう! – Arzeimuth

1
'struct std::pair' has no member named 'getText' 

イテレータが返すものは、オブジェクトではなく、std :: pairです。ペアの最初の要素がキー、2番目が値なので、値を取得する必要があります。次にメソッド:it->second->method()を呼び出します。

+1

私はそのデータにアクセスする方法を理解しようとしていましたが、それは間違いなく助けになりました。ありがとう! – Arzeimuth

関連する問題