std::list<T,Allocator>::merge
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 的元素,並且 *this 和 other 中等效元素的順序不會改變。
沒有迭代器或引用失效。從 *this 移動的元素的指標和引用,以及引用這些元素的迭代器,將引用 *this 中的相同元素,而不是 other 中的元素。
如果 *this 或 other 未根據對應的比較器排序,或者 get_allocator() != other.get_allocator(),則行為未定義。
目錄 |
[編輯] 引數
其他 | - | 要合併的另一個容器 |
comp | - | 比較函式物件(即滿足 Compare 要求的物件),如果第一個引數“小於”(即“先於”)第二個引數,則返回 true。 比較函式的簽名應等效於以下內容 bool cmp(const Type1& a, const Type2& b); 雖然簽名不需要包含 const&,但函式不得修改傳遞給它的物件,並且必須能夠接受型別(可能是 const) |
型別要求 | ||
-Compare 必須滿足 Compare 的要求。 |
[編輯] 返回值
(無)
[編輯] 異常
如果因任何原因丟擲異常,這些函式沒有效果(強異常安全保證)。除非異常來自比較。
[編輯] 複雜度
如果 other 指向與 *this 相同的物件,則不執行任何比較。
否則,給定 N 為 std::distance(begin(), end()),R 為 std::distance(other.begin(), other.end())
[編輯] 示例
#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 | *this 和 other 指向 相同物件時的效果未指定 |
指定為空操作 |
LWG 1207 | C++98 | 迭代器和/或引用是否會失效不明確 | 保持有效 |
LWG 1215 | C++98 | 如果 get_allocator() != other.get_allocator(),則無法保證 O(1) 節點移動 |
在這種情況下,行為是 未定義的 |
LWG 3088 | C++98 | operator< 可能對指標元素行為不當 | 實現定義 使用嚴格全序 |
[編輯] 另見
從另一個 list 移動元素(public 成員函式) | |
歸併兩個已排序的範圍 (函式模板) | |
就地歸併兩個有序範圍 (函式模板) | |
(C++20) |
歸併兩個已排序的範圍 (演算法函式物件) |
(C++20) |
就地歸併兩個有序範圍 (演算法函式物件) |