首页 > 解决方案 > 对 C++ 列表的基于索引的访问

问题描述

出于多种原因,我需要使用 C++ 列表(不是向量),但需要对元素进行基于索引的访问。

我想出了这样的事情:

point* point1i = std::next(listPoints.begin(), i);
point* point2i = std::next(listPoints.begin(), i + 1);

wherepoint是在别处声明的类并且i是整数。

但是当我编译我得到这个错误:

error: cannot convert ‘std::_List_iterator<point*>’ to ‘point*’ in initialization

我在这里做错了什么?

谢谢!

标签: c++

解决方案


listPoints.begin()std::next处理迭代器。由于您似乎有一个std::list<point *>并且需要该元素,因此只需取消引用所述迭代器:

point* point1i = *std::next(listPoints.begin(), i);
point* point2i = *std::next(listPoints.begin(), i + 1);

推荐阅读