std::forward_list merge() 方法
- 自 C++11 起
// (1) Non const version only
void merge( forward_list& other );
// (1) Non const version only
void merge( forward_list&& other );
// (2) Non const version only
template <class Compare>
void merge( forward_list& other, Compare comp );
// (2) Non const version only
template <class Compare>
void merge( forward_list&& other, Compare comp );
将两个已排序的列表合并为一个。
没有元素被复制。操作完成后,容器 other
将变为空的。
如果 other
指向与 *this
相同的对象,则该函数不执行任何操作。
此操作是稳定的:对于两个列表中等价的元素,来自 *this
的元素应始终位于来自 other
的元素之前,并且 *this
和 other
的等价元素的顺序不会改变。
- (1) 使用
operator<
比较元素。 - (2) 使用给定的比较函数
comp
。
没有迭代器或引用会失效,唯一的例外是移动元素的迭代器现在指向 *this
,而不是 other
。
如果 get_allocator() != other.get_allocator()
,则行为未定义
列表应按升序排序。
参数
-
other
- 要交换内容的容器 -
comp
- 比较函数对象,当第一个参数小于第二个参数时返回true
。比较函数的签名应等效于以下内容
bool cmp( const Type1& a, const Type2& b )
虽然签名不需要
const&
,但函数不得修改传递给它的对象,并且必须能够接受类型(可能为 const)Type1
和Type2
的所有值,而不考虑值类别(因此,不允许使用Type1&
,也不允许使用Type1
,除非对于Type1
移动等价于复制 (自 C++11 起))。Type1
和Type2
的类型必须使得forward_list<T, Allocator>::const_iterator
类型的对象可以被解引用,然后隐式转换为两者。
返回值
(无)
复杂度
最多进行 std::distance(begin(), end()) + std::distance(other.begin(), other.end()) - 1
次比较。
异常
如果抛出异常,此函数没有影响(强异常保证),除非异常来自比较函数。
示例
#include <iostream>
#include <forward_list>
std::ostream& operator<<(std::ostream& ostr, const std::forward_list<int>& list)
{
for (const auto &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