通过插入保持 std::list 迭代器有效

2022-01-10 00:00:00 iterator c++ stdlist

注意:这不是我应该使用列表还是双端队列"的问题.面对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;
}

不优雅,但应该可以.

相关文章