Keeping std::list iterators valid through insertion(通过插入保持 std::list 迭代器有效)
问题描述
注意:这不是我应该使用列表还是双端队列"的问题.面对insert()
,这是一个关于迭代器有效性的问题.
Note: This is not a question whether I should "use list or deque". It's a question about the validity of iterators in the face of insert()
.
这可能是一个简单的问题,我只是太密集了,看不到正确的方法.我正在实现(无论好坏)网络流量缓冲区作为 std::list<char>buf
,并且我将当前的读取位置保持为迭代器 readpos
.
This may be a simple question and I'm just too dense to see the right way to do this. I'm implementing (for better or worse) a network traffic buffer as a std::list<char> buf
, and I'm maintaining my current read position as an iterator readpos
.
当我添加数据时,我会做类似的事情
When I add data, I do something like
buf.insert(buf.end(), newdata.begin(), newdata.end());
我现在的问题是,如何保持 readpos
迭代器有效?如果它指向旧 buf
的中间,那么它应该没问题(通过 std::list 的迭代器保证),但通常我可能已经读取并处理了所有数据并且我有 readpos == buf.end()
.插入后,我希望 readpos
always 指向下一个未读字符,如果插入应该是第一个插入的字符.
My question is now, how do I keep the readpos
iterator valid? If it points to the middle of the old buf
, then it should be fine (by the iterator guarantees for std::list), but typically I may have read and processed all data and I have readpos == buf.end()
. After the insertion, I want readpos
always to point to the next unread character, which in case of the insertion should be the first inserted one.
有什么建议吗?(只需将缓冲区更改为 std::deque<char>
,这似乎更适合该任务,如下所示.)
Any suggestions? (Short of changing the buffer to a std::deque<char>
, which appears to be much better suited to the task, as suggested below.)
更新:通过 GCC4.4 的快速测试,我观察到 deque 和 list 在 readpos = buf.end()
方面的行为不同:在插入后最后, readpos 在列表中被破坏,但指向双端队列中的下一个元素.这是标准保证吗?
Update: From a quick test with GCC4.4 I observe that deque and list behave differently with respect to readpos = buf.end()
: After inserting at the end, readpos is broken in a list, but points to the next element in a deque. Is this a standard guarantee?
(根据 cplusplus,任何 deque::insert() 使所有迭代器失效.这不好.也许使用计数器比迭代器更好地跟踪双端队列中的位置?)
(According to cplusplus, any deque::insert() invalidated all iterators. That's no good. Maybe using a counter is better than an iterator to track a position in a deque?)
推荐答案
if (readpos == buf.begin())
{
buf.insert(buf.end(), newdata.begin(), newdata.end());
readpos = buf.begin();
}
else
{
--readpos;
buf.insert(buf.end(), newdata.begin(), newdata.end());
++readpos;
}
不优雅,但应该可以.
这篇关于通过插入保持 std::list 迭代器有效的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:通过插入保持 std::list 迭代器有效
基础教程推荐
- 为什么语句不能出现在命名空间范围内? 2021-01-01
- Windows Media Foundation 录制音频 2021-01-01
- 使用从字符串中提取的参数调用函数 2022-01-01
- 如何在不破坏 vtbl 的情况下做相当于 memset(this, ...) 的操作? 2022-01-01
- 管理共享内存应该分配多少内存?(助推) 2022-12-07
- 如何使图像调整大小以在 Qt 中缩放? 2021-01-01
- 为 C/C++ 中的项目的 makefile 生成依赖项 2022-01-01
- 在 C++ 中循环遍历所有 Lua 全局变量 2021-01-01
- 从 std::cin 读取密码 2021-01-01
- 如何“在 Finder 中显示"或“在资源管理器中显 2021-01-01