此迭代器代码中发生了什么?

What is occuring in this iterator code?

本文关键字:什么 发生了 迭代器 代码      更新时间:2023-10-16

我对以下两个迭代器在下面的代码中指向的内容感到非常困惑。

list<fieldT>::iterator steeperField = currentField;
list<fieldT>::iterator shallowerField = 
activeFields.insert(currentField, *currentField);

如果我们假设 activeFields(这些迭代器所属的列表)的索引为 0,1,2(count=3),并且当前字段目前指向 1。然后我想:

  1. 陡峭字段设置为索引 1。
  2. 字段 T 插入到索引 1 处的列表中,并返回从索引 1 开始的迭代器。

因此,陡峭的场应指向与浅场相同的位置。这似乎不是正在发生的事情:shallowerField似乎指向索引2。为什么?


activeFields是作为list<fieldT> & activeFields传递的参数。currentField是作为list<fieldT>::iterator & currentField传递的参数。currentField最初是通过呼叫currentField = activeFields.begin();启动的。

当我简化程序时,我得到了我期望的结果(没有断言失败):

#include <list>
#include <iostream>
#include <cassert>
using std::list;
std::ostream& operator<<(std::ostream& os, const list<char>& l)
{
os << '{';
for (auto el : l)
os << el << ',';
os << '}';
return os;
}
int main()
{
list<char> l{'a', 'b', 'c'};
list<char>::iterator insertAt { std::next(std::begin(l)) }; // 'b'
std::cout << l << 'n';
list<char>::iterator newEl { l.insert(insertAt, 'd') };
std::cout << l << 'n';
assert(std::distance(std::begin(l), insertAt) == 2);
assert(std::distance(std::begin(l), newEl)    == 1);
}

这让我相信我在你的问题中遗漏了一些东西,所以我把它表述为这篇文章,并推断出你的问题:

因此,陡峭的场应指向与浅场相同的位置。

不,不应该。steeperField是被向右洗牌的旧元素;shallowField是你的新元素。迭代器不是容器中的固定索引;它们链接到元素。在链表中,这意味着当您在元素之前插入新元素时,它们会跟随元素。

这似乎不是正在发生的事情:shallowerField似乎指向索引2。为什么?

它没有。shallowerField指向索引 1,因为它应该。steeperField指向索引 2,也应该如此。

总之,当您进行测量时出了点问题

首先让我们讨论一下函子声明

iterator insert(const_iterator position, const T& x);

它在迭代器位置之前插入元素 x,并返回引用插入元素的迭代器。

在您的示例中,currentField; 是一个迭代器,它引用列表中的某个元素。 *currentField 是元素的值。现在

activeFields.insert(currentField, *currentField)

在此元素之前插入与 currentField 引用的元素的值相同的值。事实上,它相对于当前字段将值传播到左侧;

如果我们假设 currentField 对应于列表 { 0,1,2 } 中的索引 1,那么在操作后,列表将看起来像 { 0,1,1, 2 },迭代器 shallowerField 将引用第一个 1,即它对应于索引 1。

至于你的说法

这似乎不是正在发生的事情:浅田似乎 指向索引 2。为什么?

那么正确答案是"似乎",那就是它只在你看来。您应该展示一个简单的编译示例来演示这种情况。

这是一个例子

std::list<int> l = { 0, 1, 2 };
std::list<int>::const_iterator position = std::next( l.cbegin() );
std::cout << std::distance( l.cbegin(), position ) << std::endl;
std::list<int>::iterator result = l.insert( position, *position );
std::cout << std::distance( l.begin(), result ) << std::endl;

输出是

1
1