如何将迭代器类型转换为其原始结构
How to typcast an iterator to its original structure
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;
}
相关文章:
- 如何循环打印顶点结构
- 通过方法访问结构
- 使用不带参数的函数访问结构元素
- 预处理器:插入结构名称中的前一个行号
- 为什么在没有显式默认构造函数的情况下,将另一个结构封装在联合中作为成员的结构不能编译
- 孤立代码块在结构中引发异常
- 有什么方法可以遍历结构吗
- 服务器客户端通过原始数据错误C 发送接收结构
- 在模板实例化期间获取原始结构/类名C++
- 配置 AVCodecContext 结构以从原始 PCM 编码到 u-law
- 共享指针和回调注册的结构.由于我之外的原因调用回调时,原始指针值发生了变化
- 结构转换为原始字符问题
- 如何在不更改原始 tm 结构的情况下使用 mktime()
- 如何将迭代器类型转换为其原始结构
- 实现数据结构时的智能指针或原始指针
- 如何在不更改原始数组的情况下对指向结构的指针数组进行排序
- C++-WINAPI-缺少原始输入特定的函数和结构
- c++操作结构体的原始数据
- 对数据结构进行排序并保存原始索引的记录
- 通过套接字发送和接收原始结构是否不安全