【问题标题】:How to move a range of element in a list to the front of an element also in the same list?如何将列表中的一系列元素移动到同一列表中元素的前面?
【发布时间】: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 != 首先,但这会导致无限循环。发生这种情况的原因是什么,如何解决?

【问题讨论】:

    标签: c++ list


    【解决方案1】:

    实际上是 pos != first

    没有。给定first = ++pospos 递增并分配给first。它们是等价的,pos 在 [first,last) 范围内。

    我想你想要first = std::next(pos);

    LIVE

    【讨论】:

    • 我刚刚找到了这个问题的原因,但还是谢谢你。 :)
    【解决方案2】:

    这个问题有点隐蔽。问题在于first = ++pos。这导致first == pos,使splice成为UB

    解决方案:

    auto pos = find(ls.cbegin(), ls.cend(), 5), first = pos;
    ls.splice(pos, ls, ++first, ls.end());
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2019-10-30
      • 2011-10-22
      • 2021-10-18
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多