std::list实现数据向前移动

可以使用std::list的成员方法splice来实现数据的移动。其声明的一种形式为

void splice( const_iterator pos, list&& other, const_iterator it );

表示将other中位于it内容切片(取出并插入到)*thispos之前。(有些博客说是之后

实例

假设我们想要将不重复数组中值为3的数据前移一位。

#include <iostream>
#include <list>
#include <algorithm>

void printList(std::list<int>& l) {
    for (int i : l) {
        std::cout << i << " ";
    }
    std::cout << std::endl;
}

int main() {
    std::list<int> l{1, 2, 3, 4};
    printList(l);
    // 想要将值为3的数据上移一次
    auto srcIter = std::find(l.begin(), l.end(), 3);
    auto dstIter = std::next(srcIter, -1);
    l.splice(dstIter, l, srcIter);
    printList(l);
}

其输出结果为

1 2 3 4 
1 3 2 4 

注意,慎重使用iter++,这会移动你的迭代器。

posted @ 2023-02-10 16:22  warindy  阅读(175)  评论(0)    收藏  举报