将两个list链表通过merge合并时注意的三个有关问题

将两个list链表通过merge合并时注意的三个问题

注意:1)merge()是将两个有序的链表合并成另一个有序的链表,如果有一个链表不是有序的那么在执行代码时会报错:说链表不是有序的。

2)还有,两个链表中的内容排序顺序与合并时采用的排序顺序必须一致,如果不一致,也会报错,说链表不是有序的。如想要降序合并两个链表,那么合并前的两个链表也必须是按降序排列的。

3)另外,当执行完merge()后,右边的链表将变为空。

 

例子:list<int> v1, v2;

v2.merge(v1); //按照默认排序方法合并,即按照升序

v2.merge(v1,greater<int>()); //按照降序合并

#include "stdafx.h"

#include <iostream>

#include <list>

#include <algorithm>

using namespace std;

 

 

int_tmain(int argc, _TCHAR* argv[])

{

    list<int> c1,c2,c3;

    c1.push_back(3);

    c1.push_back(6);

    c2.push_back(2);

    c2.push_back(4);

    c3.push_back(5);

    c3.push_back(1);

 

    cout<<"c1="<<endl;

    copy(c1.begin(),c1.end(),ostream_iterator<int>(cout,""));

    cout<<endl;

    cout<<"c2="<<endl;

    copy(c2.begin(),c2.end(),ostream_iterator<int>(cout,""));

    cout<<endl;

    c2.merge(c1);//按照默认排序,即升序合并

    cout<<"After merging c1 and c2 with defaulting sort>: c2=:"<<endl;

    copy(c2.begin(),c2.end(),ostream_iterator<int>(cout,""));

    cout<<endl;

    cout<<"After merge c1 and c2>: c1="<<endl;

    copy(c1.begin(),c1.end(),ostream_iterator<int>(cout,""));

    cout<<"可见合并后c1中没有内容了"<<endl;

    cout<<"c3="<<endl;

    copy(c3.begin(),c3.end(),ostream_iterator<int>(cout,""));

    cout<<endl;

    c2.reverse();//要想按照降序合并,则必须两个链表都为降序

    c2.merge(c3,greater<int>()); //按照降序合并

   

    cout<<"After merging c1 and c3 with defaulting sort>:c2=: "<<endl;

    copy(c2.begin(),c2.end(),ostream_iterator<int>(cout,""));

    cout<<endl;

 

    return 0;

}

执行结果:

将两个list链表通过merge合并时注意的三个有关问题