【问题标题】:How to typcast an iterator to its original structure如何将迭代器类型转换为其原始结构
【发布时间】:2013-10-06 06:26:15
【问题描述】:
        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 类型转换为实际的数据结构指针?这样我至少可以编写像point.xpoint.y 这样的代码。

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

【问题讨论】:

    标签: c++ list pointers stl iterator


    【解决方案1】:

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

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-07-14
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-12-19
      相关资源
      最近更新 更多