命名空间
变体
操作

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

来自 cppreference.cn
< cpp‎ | container‎ | 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(),则行为未定义。

目录

[编辑] 参数

other - 要合并的另一个容器
comp - 比较函数对象(即满足 Compare 要求的对象),如果第一个参数小于(即排序在之前)第二个参数,则返回 ​true

比较函数的签名应等效于以下形式

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

虽然签名不需要具有 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++ 标准。

DR 应用于 已发布行为 正确行为
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 移动元素
(公共成员函数) [编辑]
合并两个已排序的范围
(函数模板) [编辑]
原地合并两个已排序的范围
(函数模板) [编辑]
合并两个已排序的范围
(算法函数对象)[编辑]
原地合并两个已排序的范围
(算法函数对象)[编辑]