容器链表的insert()方法和splice()方法的区别
如:
#include <iostream>
#include <list>
using namespace std;
void main()
{
list<int> A;
list<int> B;
list<int>::iterator ititer;
A.push_back(2);
A.push_back(3);
A.push_back(4);
int num[5]={1,2,3,4,5};
B.insert(B.begin(),num,num+5);
cout<<"A:";
for(ititer=A.begin();ititer!=A.end();++ititer)
{
cout<<*ititer;
}
cout<<endl;
cout<<"B:";
for(ititer=B.begin();ititer!=B.end();++ititer)
{
cout<<*ititer;
}
cout<<endl;
B.splice(B.end(),A);
cout<<"the new A:";
for(ititer=A.begin();ititer!=A.end();++ititer)
{
cout<<*ititer;
}
cout<<endl;
cout<<"the new B:";
for(ititer=B.begin();ititer!=B.end();++ititer)
{
cout<<*ititer;
}
cout<<endl;
}
result:
A:234
B:12345
the new A:
the new B:12345234
Press any key to continue
区别:insert将list对象的副本插入到目标区域中,而splice是将该对象直接移到目标地址。通俗地说前者是复制,粘贴。后者是剪切,粘贴。用splice时当B与A合并后,B就为空。但是要记住:迭代器仍然指向原来的位置,即使原来的元素不存在了。
下面是merge()合并两个链表的方法,先写结果
A:234
B:16345
A:
B:12346345
Press any key to continue
它的意思是将A合并到B的时候先在B中一个一个检查如果查到比A小的数,就不变,查到比A的数就将B的这些数插入进去.所以这种合并方法与splice()差别就在排序上面
#include <iostream>
#include <list>
using namespace std;
void main()
{
list<int> A;
list<int> B;
list<int>::iterator ititer;
A.push_back(2);
A.push_back(4);
A.push_back(3);
int num[5]={1,6,3,4,5};
B.insert(B.begin(),num,num+5);
cout<<"A:";
for(ititer=A.begin();ititer!=A.end();++ititer)
{
cout<<*ititer;
}
cout<<endl;
cout<<"B:";
for(ititer=B.begin();ititer!=B.end();++ititer)
{
cout<<*ititer;
}
cout<<endl;
B.merge(A);//合并时按照顺序,但又不是将A和B一起进行排序
cout<<"A:";
for(ititer=A.begin();ititer!=A.end();++ititer)
{
cout<<*ititer;
}
cout<<endl;
cout<<"B:";
for(ititer=B.begin();ititer!=B.end();++ititer)
{
cout<<*ititer;
}
cout<<endl;
}