如何将迭代器类型转换为其原始结构

How to typcast an iterator to its original structure

本文关键字:原始 结构 类型转换 迭代器      更新时间:2023-10-16
        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.x一样编写代码,至少可以说point.y

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

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

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