C++中list:splice函数详解

C++中list:splice函数详解

splice()函数是list中的一个剪贴函数,将另外一个list中的元素剪贴到本list中。共有3个重载:

list1为要操作的list;
list2为被剪去的list;
position为list1中的某个位置的迭代器

list1调用splice函数

  1. list1.splice(position, list2): 将list2中的所有元素剪贴到list1的position位置;
  2. list1.splice(position, list2, iter): 将list2中某个位置的迭代器iter指向的元素剪贴到list1中的position位置;
  3. list1.splice(position, list2, iter1, iter2): 将list2中的某一段位置iter1 ~ iter2的元素剪贴到list1中的position位置

测试代码

#include 
#include 
#include 
using namespace std;

int main() {
	list<int> list1 = { 1, 2, 3, 4, 5 };
	list<int> list2 = { 11, 12, 13, 14, 15 };

	list<int>::iterator iter = list1.begin();
	iter++;

	//把list2全部剪贴到list1的iter位置
	list1.splice(iter, list2);
	cout << "list1: ";
	for (auto& num : list1) {
		cout << num << " ";
	}
	cout << endl;

	cout << "list2: ";
	for (auto& num : list2) {
		cout << num << " ";
	}
	cout << endl;

	cout << "---------------------" << endl;

	list<int> list3 = { 1, 2, 3, 4, 5 };
	list<int> list4 = { 11, 12, 13, 14, 15 };
	list<int>::iterator iter1 = list4.begin();
	iter1++;

	//把list4中iter1位置处的值剪贴到list3的list3.begin()位置
	list3.splice(list3.begin(), list4, iter1);
	cout << "list3: ";
	for (auto& num : list3) {
		cout << num << " ";
	}
	cout << endl;
	cout << "list4: ";
	for (auto& num : list4) {
		cout << num << " ";
	}
	cout << endl;

	cout << "-----------------------" << endl;

	list<int> list5 = { 1, 2, 3, 4, 5 };
	list<int> list6 = { 11, 12, 13, 14, 15 };
	list<int>::iterator iter2 = list6.begin();
	list<int>::iterator iter3 = iter2;
	iter3++; iter3++; iter3++;

	//把list6中从iter2到iter3的元素剪贴到list5中的list5.begin()处
	list5.splice(list5.begin(), list6, iter2, iter3);
	cout << "list5: ";
	for (auto& num : list5) {
		cout << num << " ";
	}
	cout << endl;
	cout << "list6: ";
	for (auto& num : list6) {
		cout << num << " ";
	}
	cout << endl;

	return 0;
}

输出:

list1: 1 11 12 13 14 15 2 3 4 5
list2:
---------------------
list3: 12 1 2 3 4 5
list4: 11 13 14 15
-----------------------
list5: 11 12 13 1 2 3 4 5
list6: 14 15

你可能感兴趣的:(C++,c++,列表)