1.功能:
splice是将list X中的元素 剪切 到list Y中。 [注意:是“剪切”,也就是说list X 中元素会减少]
2.splice函数重载三种形式:
| entire list (1) |
void splice (iterator position, list& x);
|
|---|
| single element (2) |
void splice (iterator position, list& x, iterator i);
|
|---|
| element range (3) |
void splice (iterator position, list& x, iterator first, iterator last);
|
|---|
3 函数具体说明:
第一种形式,从"entire list"可以得知, 是将整个list X剪切掉.
第二种形式,从"single element"可以得知, 是将整个list X中的一个元素剪切过去,具体是哪个元素有X中的迭代器i 指定.
第三种形式,从"element range"可以得知, 是将整个list X中一定范围的元素剪切过去,有迭代器first 和end指定。[注意:剪切的元素不包括end所指向的]
那么List X中剪切的元素 放到List Y 哪里? 由第一个参数position指定.同样类型也是迭代器.
4 测试代码:
#include <iostream>
#include <list>
int main ()
{
std::list<int> mylist1, mylist2;
std::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迭代器所指的内容已经剪切到mylist2中了,也就是说it所指向的元素不存在了,那么这个it中的值也就是一个无效的值
it = mylist1.begin();
std::advance(it,3); // "it" points now to 30
mylist1.splice ( mylist1.begin(), mylist1, it, mylist1.end());
// mylist1: 30 3 4 1 10 20
std::cout << "mylist1 contains:";
for (it=mylist1.begin(); it!=mylist1.end(); ++it)
std::cout << ' ' << *it;
std::cout << '\n';
std::cout << "mylist2 contains:";
for (it=mylist2.begin(); it!=mylist2.end(); ++it)
std::cout << ' ' << *it;
std::cout << '\n';
return 0;
}
|
|
Output:
mylist1 contains: 30 3 4 1 10 20
mylist2 contains: 2
|