2
        list<CPoint> l;

        l.push_back( CPoint(1,2) );
        l.push_back( CPoint(30,40) );
        l.push_back( CPoint(4,6) );
        l.push_back( CPoint(70,80) );

        CPoint * point = 0;

        for ( list<CPoint>::iterator iter = l.begin();
                iter != l.end();
                iter++)
        {
            cout << iter->x << " , "  << iter->y << endl;

            // compilation error, I can't typcast it like below?
            point  = (CPoint *) iter;
        }

上面的问题是如何将iter循环中的 in 类型转换为实际的数据结构指针?这样我就可以编写类似的代码point.xpoint.y至少可以这么说。

以上是我编写的演示代码,但实际上我在搜索功能中有此代码。如果在列表中找到一个项目,它将返回指向该项目的指针,否则为 NULL。为了取回该指针,我需要将迭代器解引用回底层数据结构指针,但如何?谢谢。

4

1 回答 1

3

要修复语法错误,您需要取消引用迭代器,然后从下面的对象中获取地址:

point  =  &*iter;

你最好只使用std::find/std::find_if并存储从 std::list 返回的迭代器。

auto it = std::find_if(l.begin(), l.end(), 
                       [](const CPoint& cp) { return cp.x == 1 && cp.y == 2; } );

if (it != l.end()) // test iterator to see is desired CPoint is found
{
    std::cout << (*it).x << " " << (*it).y << std::endl;
}
于 2013-10-06T06:29:33.877 回答