【问题标题】:STL map, using iterators and pointers of classesSTL 映射,使用迭代器和类指针
【发布时间】:2012-04-23 05:26:29
【问题描述】:

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

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

【问题讨论】:

    标签: c++ map stl iterator


    【解决方案1】:

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

    【讨论】:

    • 我肯定知道现在发生了什么。谢谢!
    【解决方案2】:

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

    它被摧毁了。

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

    【讨论】:

    • 也许我在使用指针时很笨拙。感谢您指出这一点!
    【解决方案3】:
    'struct std::pair' has no member named 'getText'
    

    表示迭代器返回的是std::pair,而不是你的对象; pair的第一个元素是key,第二个是value,所以需要获取value,然后调用方法:it-&gt;second-&gt;method()

    【讨论】:

    • 我试图弄清楚如何访问这些数据,这肯定也有帮助。谢谢!
    猜你喜欢
    • 2011-04-02
    • 1970-01-01
    • 2012-01-28
    • 2011-05-29
    • 2017-08-08
    • 1970-01-01
    • 2011-01-09
    • 2011-05-01
    • 2014-12-05
    相关资源
    最近更新 更多