命名空间
变体
操作

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

来自 cppreference.cn
< cpp‎ | 容器‎ | forward list
 
 
 
 
void merge( forward_list& other );
(1) (C++11 起)
void merge( forward_list&& other );
(2) (C++11 起)
template< class Compare >
void merge( forward_list& other, Compare comp );
(3) (C++11 起)
template< class Compare >
void merge( forward_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&,但函数不得修改传递给它的对象,并且必须能够接受类型(可能是 const)Type1Type2 的所有值,而与 值类别 无关(因此,不允许使用 Type1&,除非对于 Type1,移动等效于复制,否则也不允许使用 Type1(C++11 起))。
类型 Type1Type2 必须使得类型为 forward_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 <forward_list>
 
std::ostream& operator<<(std::ostream& ostr, const std::forward_list<int>& list)
{
    for (const int i : list)
        ostr << ' ' << i;
    return ostr;
}
 
int main()
{
    std::forward_list<int> list1 = {5, 9, 1, 3, 3};
    std::forward_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 2045 C++11 如果以下情况,则不能保证 O(1) 节点移动
get_allocator() != other.get_allocator()
行为是
在这种情况下未定义
LWG 3088 C++11 *thisother 指代
同一对象时的效果未指定
operator< 可能对指针元素行为不当
指定为无操作
实现定义
使用严格全序

[编辑] 参见

从另一个 forward_list 移动元素
(公共成员函数) [编辑]
合并两个已排序范围
(函数模板) [编辑]
原地合并两个有序范围
(函数模板) [编辑]
合并两个已排序范围
(算法函数对象)[编辑]
原地合并两个有序范围
(算法函数对象)[编辑]