簡體   English   中英

STL映射,使用類的迭代器和指針

[英]STL map, using iterators and pointers of classes

我在使用迭代器訪問地圖內的數據時遇到麻煩。 我想通過使用迭代器返回插入到映射中的所有值。 但是,當我使用迭代器時,它不會確認該類實例中的任何成員。

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 ===|

我的MapVertex類中有一個名為getText()的訪問成員,該訪問成員返回其中的數據。

要修復編譯器錯誤,您需要執行- it->second->getText()因為*iteratorpair<string, MapVertex*> 但是您的代碼中還有其他問題。 在插入地圖時,您正在向其中插入局部變量的地址。 在您嘗試使用for循環迭代地圖時,此地址將無效。 我建議您將地圖聲明為std::map<string, MyVertex>以便在將地圖插入MyVertex的副本時將其插入地圖。

tmpVert是問題所在。 看,您在堆棧上創建了它。 在每個for循環的結尾將其銷毀。

它被破壞了。

因此,您的mapGraph持有指向不存在的對象的指針。

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

意味着迭代器返回的是std :: pair,而不是您的對象; 該對中的第一個元素是鍵,第二個是值,因此您需要獲取值,然后調用方法: it->second->method()

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM