【发布时间】:2021-07-25 12:15:10
【问题描述】:
我想将列表中的一系列元素移动到同一列表中元素的前面。我正在尝试使用
list.splice(const_iterator pos, list &other, const_iterator first, const_iterator last)
实现这一点。
这是我的代码:
list<int> ls{1, 2, 3, 4, 5, 6, 7, 8, 9};
// try to move [6, 9] to the front of 5
auto pos = find(ls.cbegin(), ls.cend(), 5), first = ++pos;
ls.splice(pos, ls, first, ls.end());
cppreference 说:
将 [first, last) 范围内的元素从 other 转移到 *this。这些元素被插入到 pos 指向的元素之前。如果 pos 是 [first,last) 范围内的迭代器,则行为未定义。
实际上 pos != 首先,但这会导致无限循环。发生这种情况的原因是什么,如何解决?
【问题讨论】: