同时访问列表中的一个元素及其后继元素
Accessing an element and its successor in a list at the same time
我有一个列表,当迭代它时,我想同时访问迭代器上的元素和迭代器+1上的下一个元素。下面是我的尝试:
std::list<Team*> teamlist = league.GetTeamMembers();
for (std::list<Team*> ::iterator iterator = teamlist.begin(); iterator != teamlist.end(); std::advance(iterator,2))
{
match(*(*iterator), *(*(++iterator)));
}
match函数对迭代器不做任何操作,它只是从迭代器中获取一些球队的值来计算匹配结果。
但是c++迭代器不起作用,因为match函数中的元素仍然是相同的。我该怎么做呢?
传递迭代器并在同一遍历中对迭代器进行操作(如迭代器的自增操作)会导致未定义的行为。在执行此类操作时,您应该了解诸如序列点之类的某些概念。
此外,您还可以查看此链接。我建议您在传递到函数后移动操作符的增量。
您可以避免在循环的增量部分增加迭代器,并在主体中点它:
std::list<Team*> teamlist = league.GetTeamMembers();
for (std::list<Team*> ::iterator it = teamlist.begin();
it != teamlist.end(); /*Nothing here*/)
{
match(*(*it), *(*(++it))); //Which parameter expression is evaluated first isn't determined
++it;
...
...
编辑:正如FredOverflow所指出的,匹配参数表达式的求值不能保证按从左到右的顺序运行。为了避免这种危险情况:
std::list<Team*> teamlist = league.GetTeamMembers();
for (std::list<Team*> ::iterator it = teamlist.begin();
it != teamlist.end(); /*Nothing here*/)
{
Team *pa = *it;
Team *pb = *(++it);
match(*pa, *pb);
++it;
...
...
迭代器加两次,第一次是在for循环的开头:
std::advance(it,2)
然后在循环体中执行:
++it
这真的是你想要的吗?这看起来很让我困惑。
如果你想让它旁边的元素,但不希望增加它,最好使用:
auto nextIt = std::next(it);
Also: match函数做什么?你确定它的实现是正确的,而不是bug的来源吗?
希望有帮助
亚历山大相关文章:
- lower_bound()返回最后一个元素
- 使用std::transform将一个范围的元素添加到另一个范围中
- 我想访问std::unique_ptr中的一个特定元素
- 基于范围的 for 循环:迭代使用一个元素扩展的向量
- 使用运算符 [] 引用 std::vector 上最后一个元素时出现问题<>
- 删除映射和分割错误中的一个过去结束元素
- Lower_bound不适用于具有 3 个元素的向量的最后一个元素
- 查找数组中第一个最小值和最后一个最大值元素之间的算术平均值
- 检查 2D 网格的某个元素是否与另一个元素共享对角线、水平线或垂直线
- 如何创建一个所有行大小不同的 2D 数组,并且用户将指定每行将有多少个元素?
- 仅显示链表的最后一个元素
- 为什么在 std::map 上移动无法将元素从一个映射移动到另一个映射
- 查找最小的下一个更大的元素
- push_back通过自行创建的对象获取最后一个元素的向量
- 使用 map.end() 访问 map 的最后一个元素
- 如何知道地图中的最后一个元素是否被删除?
- 选择一个元素而不是一个对象的数组的原因
- std::矢量保存 只推送最后一个元素
- 为什么这个选择排序算法仍然切换一个元素,当它已经是其他元素中最小的元素时?
- 动态分配列表 - 创建一个函数,用于删除所有包含偶数值的元素