STL映射,使用迭代器和类的指针

时间:2012-04-23 05:26:30

标签: c++ map stl iterator

我无法使用迭代器访问地图中的数据。我想通过使用迭代器返回插入到地图中的所有值。但是,当我使用迭代器时,它不会确认它已经过去的类实例中的任何成员。

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()的访问成员,它返回其中的数据。

3 个答案:

答案 0 :(得分:4)

要修复编译器错误,您需要执行it->second->getText(),因为*iteratorpair<string, MapVertex*>。但是代码中还有其他问题。插入地图时,您将向其中插入局部变量的地址。当您尝试使用for循环迭代地图时,此地址将无效。我建议你将地图声明为std::map<string, MyVertex>,以便在插入地图时,将MyVertex的副本插入到地图中。

答案 1 :(得分:2)

tmpVert是问题所在。看,你在堆栈上创建它。它在每个for循环结束时被销毁。

它被摧毁了。

所以,你的mapGraph持有指向不存在的对象的指针。

答案 2 :(得分:1)

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

意味着迭代器返回的是std :: pair,而不是你的对象;该对的第一个元素是键,第二个是值,因此您需要获取值,然后调用方法:it->second->method()