命名空间
变体
操作

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

来自 cppreference.cn
< 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 成员函数) [编辑]
归并两个已排序的范围
(函数模板) [编辑]
就地归并两个有序范围
(函数模板) [编辑]
归并两个已排序的范围
(算法函数对象)[编辑]
就地归并两个有序范围
(算法函数对象)[编辑]