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

 
 
 
 
void merge( forward_list& other );
(1) (C++11 起)
void merge( forward_list&& other );
(1) (C++11 起)
template <class Compare>
void merge( forward_list& other, Compare comp );
(2) (C++11 起)
template <class Compare>
void merge( forward_list&& other, Compare comp );
(2) (C++11 起)

归并二个已排序链表为一个。链表应以升序排序。

不复制元素。操作后容器 other 变为空。若 other*this 指代同一对象则函数不做任何事。若 get_allocator() != other.get_allocator() ,则行为未定义。没有引用和迭代器变得非法,除了被移动元素的迭代器现在指代到 *this 中,而非到 other 中,第一版本用 operator< 比较元素,第二版本用给定的比较函数 comp

此操作是稳定的:对于二个链表中的等价元素,来自 *this 的元素始终前驱来自 other 的元素,而且 *thisother 的等价元素顺序不更改。

参数

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 类型的对象能在解引用后隐式转换到这两个类型。 ​

返回值

(无)

异常

若抛出异常,则此函数无效果(强异常保证),除非异常来自比较函数。

复杂度

至多 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 (auto &i : list) {
        ostr << " " << i;
    }
    return ostr;
}
 
int main()
{
    std::forward_list<int> list1 = { 5,9,0,1,3 };
    std::forward_list<int> list2 = { 8,7,2,6,4 };
 
    list1.sort();
    list2.sort();
    std::cout << "list1:  " << list1 << "\n";
    std::cout << "list2:  " << list2 << "\n";
    list1.merge(list2);
    std::cout << "merged: " << list1 << "\n";
}

输出:

list1:   0 1 3 5 9
list2:   2 4 6 7 8
merged:  0 1 2 3 4 5 6 7 8 9

参阅

从另一 forward_list 移动元素
(公开成员函数)