std::list<T,Allocator>::splice

来自cppreference.com
< cpp‎ | container‎ | list

void splice( const_iterator pos, list& other );
(1)
void splice( const_iterator pos, list&& other );
(1) (C++11 起)
void splice( const_iterator pos, list& other, const_iterator it );
(2)
void splice( const_iterator pos, list&& other, const_iterator it );
(2) (C++11 起)
void splice( const_iterator pos, list& other,
             const_iterator first, const_iterator last);
(3)
void splice( const_iterator pos, list&& other,
             const_iterator first, const_iterator last );
(3) (C++11 起)

从一个 list 转移元素给另一个。

不复制或移动元素,仅重指向链表结点的内部指针。get_allocator() != other.get_allocator() 时行为未定义。没有迭代器或引用会失效,指向被移动元素的迭代器保持有效,但现在指代到 *this 中,而非到 other 中。

1)other 转移所有元素到 *this 中。元素被插入到 pos 指向的元素之前。操作后容器 other 变为空。other*this 指代同一对象时行为未定义。
2)other 转移 it 指向的元素到 *this。元素被插入到 pos 指向的元素之前。
3)other 转移范围 [first, last) 中的元素到 *this。元素被插入到 pos 指向的元素之前。pos 是范围 [first,last) 中的迭代器时行为未定义。

参数

pos - 将插入内容到它之前的元素
other - 要从它转移内容的另一容器
it - 要从 other 转移到 *this 的元素
first, last - 要从 other 转移到 *this 的元素范围

返回值

(无)

异常

不抛出。

复杂度

1-2) 常数。

3) 如果 other*this 指代同一对象时是常数,否则与 std::distance(first, last) 成线性。

示例

#include <iostream>
#include <list>
 
std::ostream& operator<<(std::ostream& ostr, const std::list<int>& list)
{
    for (auto &i : list)
        ostr << " " << i;
 
    return ostr;
}
 
int main ()
{
    std::list<int> list1 = {1, 2, 3, 4, 5};
    std::list<int> list2 = {10, 20, 30, 40, 50};
 
    auto it = list1.begin();
    std::advance(it, 2);
 
    list1.splice(it, list2);
 
    std::cout << "list1:" << list1 << "\n";
    std::cout << "list2:" << list2 << "\n";
 
    list2.splice(list2.begin(), list1, it, list1.end());
 
    std::cout << "list1:" << list1 << "\n";
    std::cout << "list2:" << list2 << "\n";
}

输出:

list1: 1 2 10 20 30 40 50 3 4 5
list2:
list1: 1 2 10 20 30 40 50
list2: 3 4 5

缺陷报告

下列更改行为的缺陷报告追溯地应用于以前出版的 C++ 标准。

缺陷报告 应用于 出版时的行为 正确行为
LWG 250 C++98 到被移动的元素的引用或迭代器都会失效 它们指代或指向 *this 中相同的元素

参阅

合并二个已排序列表
(公开成员函数)
移除满足特定标准的元素
(公开成员函数)