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

STL map, using iterators and pointers of classes

本文关键字:迭代器 指针 映射 STL      更新时间:2023-10-16

我在使用迭代器访问地图中的数据时遇到问题。我想使用迭代器返回插入到映射中的所有值。但是,当我使用迭代器时,它不会确认它过去进入的类实例中的任何成员。

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

编译器输出:

lab12main.cpp||In function `int main()':|
lab12main.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(),因为*iterator是一个pair<string, MapVertex*>。但是您的代码中还有其他问题。插入到映射中时,将局部变量的地址插入到映射中。当您尝试使用循环迭代映射时,此地址将无效for。我建议您将地图声明为std::map<string, MyVertex>这样当您将MyVertex的副本插入到地图中时

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

它被摧毁了。

因此,您的mapGraph持有指向不存在对象的指针。

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

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