C++拼接方法splice

splice的功能: 将B序列中[b1, b2) 范围内的元素抽调到A序列中的a位置,这个抽调的过程中,A的长度增加了,B的长度减少了。

splice有四个参数,用法:A.splice(a, B, b1, b2)

以下是一个小示例:实现将 l1 的后几个元素和 l2 的后几个元素对调(里面为什么会用到第三方temp可以思考一下)

#include<iostream>
#include<iterator>
#include<list>
using namespace std;

template<class T>
void exchange(list<T>& l1, class list<T>::iterator p1, list<T>& l2, class list<T>::iterator p2){
	list<T> temp;
	temp.splice(temp.begin(), l1, p1, l1.end());
	l1.splice(l1.end(), l2, p2, l2.end());
	l2.splice(l2.end(), temp, temp.begin(), temp.end());
}

typedef list<int> intlist; 

int main(){
	intlist a, b;
	
	for(int i = 0; i < 6; i++){
		a.push_back(i * 2 + 1);
		b.push_back(i * 3 + 2);
	}
	cout<<"a: ";
	copy(a.begin(), a.end(), ostream_iterator<int>(cout, " "));
	cout<<endl;
	cout<<"b: ";
	copy(b.begin(), b.end(), ostream_iterator<int>(cout, " "));
	cout<<endl;
	
	cout<<"after exchanging..."<<endl;
	intlist::iterator p1 = a.begin();
	advance(p1, 3);
	intlist::iterator p2 = b.begin();
	advance(p2, 4);
	exchange(a, p1, b, p2);
	cout<<"a: ";
	copy(a.begin(), a.end(), ostream_iterator<int>(cout, " "));
	cout<<endl;
	cout<<"b: ";
	copy(b.begin(), b.end(), ostream_iterator<int>(cout, " "));
	cout<<endl;
	
	return 0;
} 
发布了82 篇原创文章 · 获赞 71 · 访问量 16万+

猜你喜欢

转载自blog.csdn.net/m0_37738114/article/details/105053168