名稱空間
變體
操作

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

來自 cppreference.com
< cpp‎ | 容器‎ | list
 
 
 
 
void splice( const_iterator pos, list& other );
(1)
void splice( const_iterator pos, list&& other );
(2) (C++11 起)
void splice( const_iterator pos, list& other, const_iterator it );
(3)
void splice( const_iterator pos, list&& other, const_iterator it );
(4) (C++11 起)
void splice( const_iterator pos, list& other,
             const_iterator first, const_iterator last);
(5)
void splice( const_iterator pos, list&& other,
             const_iterator first, const_iterator last );
(6) (C++11 起)

將元素從一個列表轉移到另一個列表。

沒有元素被複制或移動,只有列表節點的內部指標被重新指向。沒有迭代器或引用失效,指向被移動元素的迭代器仍然有效,但現在它們指向 *this,而不是 other

1,2)other 中的所有元素轉移到 *this。這些元素插入到 pos 所指向的元素之前。操作後,容器 other 變為空。
3,4)other 中由 it 所指向的元素轉移到 *this。該元素插入到 pos 所指向的元素之前。
5,6) 將範圍 [firstlast) 中的元素從 other 轉移到 *this。這些元素插入到 pos 所指向的元素之前。

若出現以下情況,行為未定義:

  • get_allocator() != other.get_allocator(),則無法保證 O(1) 節點移動,
  • 對於過載 (1,2)*thisother 指的是同一個物件,
  • 對於過載 (3,4)it 不是 other 中可解引用迭代器,或者
  • 對於過載 (5,6)
  • [firstlast) 不是 other 中的有效範圍,或者
  • pos 位於 [firstlast) 中。

目錄

[編輯] 引數

pos - 內容將被插入到的元素之前的位置
其他 - 另一個要從中轉移內容的容器
it - 要從 other 轉移到 *this 的元素
first, last - 定義要從 other 轉移到 *this 的元素範圍的迭代器對

[編輯] 返回值

(無)

[編輯] 異常

不丟擲任何異常。

[編輯] 複雜度

1-4) 常數時間。
5,6) 如果 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 中的相同元素
N2525 C++98 如果滿足以下條件,則無法保證 O(1) 的拼接操作:
get_allocator() != other.get_allocator(),則無法保證 O(1) 節點移動
在這種情況下,行為是
未定義的

[編輯] 另請參閱

歸併兩個已排序連結串列
(public member function) [編輯]
移除滿足特定標準的元素
(public member function) [編輯]