http://blog.csdn.net/bichenggui/article/details/4674900
list::splice實現list拼接的功能。將源list的內容部分或全部元素刪除,拼插入到目的list。
函數有以下三種聲明:
void splice ( iterator position, list<T,Allocator>& x ); //
void splice ( iterator position, list<T,Allocator>& x, iterator i );
void splice ( iterator position, list<T,Allocator>& x, iterator first, iterator last );
函數說明:在list間移動元素:
將x的元素移動到目的list的指定位置,高效的將他們插入到目的list並從x中刪除。
目的list的大小會增加,增加的大小為插入元素的大小。x的大小相應的會減少同樣的大小。
前兩個函數不會涉及到元素的創建或銷毀。第三個函數會。
指向被刪除元素的迭代器會失效。
參數:
position
目的list的位置,用來標明 插入位置
x
源list、
first,last
x里需要被移動的元素的迭代器。區間為[first, last).
包含first指向的元素,不包含last指向的元素。
例子:
// splicing lists
#include <iostream>
#include <list>
#include <string>
#include <algorithm>
using namespace std;
int main ()
{
list<int> mylist1, mylist2;
list<int>::iterator it;
// set some initial values:
for (int i=1; i<=4; i++)
mylist1.push_back(i); // mylist1: 1 2 3 4
for (int i=1; i<=3; i++)
mylist2.push_back(i*10); // mylist2: 10 20 30
it = mylist1.begin();
++it; // points to 2
mylist1.splice (it, mylist2); // mylist1: 1 10 20 30 2 3 4
// mylist2 (empty)
// "it" still points to 2 (the 5th element)
mylist2.splice (mylist2.begin(),mylist1, it);
// mylist1: 1 10 20 30 3 4
// mylist2: 2
// "it" is now invalid.
it = mylist1.begin();
advance(it,3); // "it" points now to 30
mylist1.splice ( mylist1.begin(), mylist1, it, mylist1.end());
// mylist1: 30 3 4 1 10 20
cout << "mylist1 contains:";
for (it=mylist1.begin(); it!=mylist1.end(); it++)
cout << " " << *it;
cout << "/nmylist2 contains:";
for (it=mylist2.begin(); it!=mylist2.end(); it++)
cout << " " << *it;
cout << endl;
list<string> dictionary, bword;
dictionary.push_back("any");
dictionary.push_back("angle");
dictionary.push_back("ajust");
dictionary.push_back("common");
dictionary.push_back("cannon");
dictionary.push_back("company");
bword.push_back("blue");
bword.push_back("banana");
bword.push_back("break");
list<string>::iterator its = dictionary.begin();
for (int i = 0; i < 3; i++)
its++;
dictionary.splice(its, bword);
copy(bword.begin(), bword.end(), ostream_iterator<string>(cout, "/n"));
return 0;
}