std::forward_list<T,Allocator>::merge
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 的元素,并且 *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 <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++ 标准。
缺陷报告 | 应用于 | 发布时的行为 | 正确的行为 |
---|---|---|---|
LWG 2045 | C++11 | 如果 *this 和 other 指向 get_allocator() != other.get_allocator(),则无法保证 O(1) 节点移动 |
在这种情况下,行为是 未定义的 |
LWG 3088 | C++11 | 同一对象时的效果未指定 无法保证 O(1) 节点移动 operator< 可能对指针元素行为不正常 |
指定为空操作 实现定义 使用严格全序 |
[编辑] 另请参阅
从另一个 forward_list 移动元素(public 成员函数) | |
归并两个已排序的范围 (函数模板) | |
就地归并两个有序范围 (函数模板) | |
(C++20) |
归并两个已排序的范围 (算法函数对象) |
(C++20) |
就地归并两个有序范围 (算法函数对象) |