此迭代器代码中发生了什么?
What is occuring in this iterator code?
我对以下两个迭代器在下面的代码中指向的内容感到非常困惑。
list<fieldT>::iterator steeperField = currentField;
list<fieldT>::iterator shallowerField =
activeFields.insert(currentField, *currentField);
如果我们假设 activeFields(这些迭代器所属的列表)的索引为 0,1,2(count=3),并且当前字段目前指向 1。然后我想:
- 陡峭字段设置为索引 1。
- 字段 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
- 此测试()中发生了什么意外过程?为什么总是覆盖 ch[0 1 2..]?
- 这C++代码中发生了什么C++(指数函数)
- 哪种方式更快?究竟发生了什么,我们没有看到什么?
- 从"LLONG_MAX 秒"构造 std::chrono::毫秒变量时发生了什么?
- 这个片段中关于 n 在 pc[i] 中的表示发生了什么
- istringstream,num1 和 num2 在这里发生了什么?
- 究竟发生了什么,我们需要在 c++ 中双重调度/访客
- 我是否能够确定在部署一个程序后发生了什么,我在数组末尾写入?
- 这个阶乘程序内部发生了什么?
- C++ - *(int**) 地址?这里发生了什么?
- C++用用户输入在循环中填充 char 数组:输入整个字符串时到底发生了什么?
- 让对象知道它创建的 show 函数中发生了什么
- 这里的矢量数组发生了什么?
- 增加顶级常量指针时发生了什么
- 当另一端将其关闭时,插座发生了什么
- C :我堆栈顶部发生了什么
- 此递归中发生了什么?我需要仅使用递归/无循环来计算和备份
- 这个 std::vector 构造函数中发生了什么
- 编译器认为 int 是一个字符串.发生了什么事情
- 无法运行简单的 std::async 和 std::future 测试程序。错误:"has initializer but incomplete type."发生了什么?