名稱空間
變體
操作

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

來自 cppreference.com
< cpp‎ | 容器‎ | list
 
 
 
 
void merge( list& other );
(1)
void merge( list&& other );
(2) (C++11 起)
template< class Compare >
void merge( list& other, Compare comp );
(3)
template< class Compare >
void merge( list&& other, Compare comp );
(4) (C++11 起)

如果 other 指向與 *this 相同的物件,則函式不執行任何操作。

否則,將 other 合併到 *this 中。兩個列表都應該已排序。不復制任何元素,並且容器 other 在合併後變為空。此操作是穩定的:對於兩個列表中的等效元素,來自 *this 的元素總是先於來自 other 的元素,並且 *thisother 中等效元素的順序不會改變。

沒有迭代器或引用失效。從 *this 移動的元素的指標和引用,以及引用這些元素的迭代器,將引用 *this 中的相同元素,而不是 other 中的元素。

1,2) 元素使用 std::less<T>()(直到 C++14)std::less<>()(自 C++14 起) 進行比較。
3,4) 元素使用 comp 進行比較。

如果 *thisother 未根據對應的比較器排序,或者 get_allocator() != other.get_allocator(),則行為未定義。

目錄

[編輯] 引數

其他 - 要合併的另一個容器
comp - 比較函式物件(即滿足 Compare 要求的物件),如果第一個引數“小於”(即“先於”)第二個引數,則返回 true

比較函式的簽名應等效於以下內容

bool cmp(const Type1& a, const Type2& b);

雖然簽名不需要包含 const&,但函式不得修改傳遞給它的物件,並且必須能夠接受型別(可能是 const)Type1Type2 的所有值,而不論其值類別(因此,不允許使用 Type1&,除非對於 Type1 移動等同於複製,否則也不允許使用 Type1(自 C++11 起))。
型別 Type1Type2 必須使得型別為 list<T, Allocator>::const_iterator 的物件可以被解引用,然後隱式轉換為這兩種型別。​

型別要求
-
Compare 必須滿足 Compare 的要求。

[編輯] 返回值

(無)

[編輯] 異常

如果因任何原因丟擲異常,這些函式沒有效果(強異常安全保證)。除非異常來自比較。

[編輯] 複雜度

如果 other 指向與 *this 相同的物件,則不執行任何比較。

否則,給定 Nstd::distance(begin(), end())Rstd::distance(other.begin(), other.end())

1,2) 最多 N+R-1 次使用 operator< 的比較。
3,4) 最多 N+R-1 次應用比較函式 comp

[編輯] 示例

#include <iostream>
#include <list>
 
std::ostream& operator<<(std::ostream& ostr, const std::list<int>& list)
{
    for (const int i : list)
        ostr << ' ' << i;
    return ostr;
}
 
int main()
{
    std::list<int> list1 = {5, 9, 1, 3, 3};
    std::list<int> list2 = {8, 7, 2, 3, 4, 4};
 
    list1.sort();
    list2.sort();
    std::cout << "list1: " << list1 << '\n';
    std::cout << "list2: " << list2 << '\n';
 
    list1.merge(list2);
    std::cout << "merged:" << list1 << '\n';
}

輸出

list1:  1 3 3 5 9
list2:  2 3 4 4 7 8
merged: 1 2 3 3 3 4 4 5 7 8 9

[編輯] 缺陷報告

下列更改行為的缺陷報告追溯地應用於以前出版的 C++ 標準。

缺陷報告 應用於 釋出時的行為 正確的行為
LWG 300 C++98 *thisother 指向
相同物件時的效果未指定
指定為空操作
LWG 1207 C++98 迭代器和/或引用是否會失效不明確 保持有效
LWG 1215 C++98 如果
get_allocator() != other.get_allocator(),則無法保證 O(1) 節點移動
在這種情況下,行為是
未定義的
LWG 3088 C++98 operator< 可能對指標元素行為不當 實現定義
使用嚴格全序

[編輯] 另見

從另一個 list 移動元素
(public 成員函式) [編輯]
歸併兩個已排序的範圍
(函式模板) [編輯]
就地歸併兩個有序範圍
(函式模板) [編輯]
歸併兩個已排序的範圍
(演算法函式物件)[編輯]
就地歸併兩個有序範圍
(演算法函式物件)[編輯]