保持std :: list迭代器通过插入有效 [英] Keeping std::list iterators valid through insertion

查看:366
本文介绍了保持std :: list迭代器通过插入有效的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

注意:这不是我应该使用list还是deque的问题。这是一个关于迭代器在 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 总是指向下一个未读的字符,如果插入的话应该是第一个插入的字符。

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在列表中被破坏,但指向deque中的下一个元素。 这是标准保证吗?

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迭代器通过插入有效的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆