欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

交换

程序员文章站 2022-07-10 18:14:58
...
//for_each() 速度快 不灵活
//transform  速度慢   非常灵活

#include<iostream>
#include<algorithm>
#include<vector>
#include<functional>
#include<deque>
#include<iterator>

using namespace std;

void print(vector<int> &l)
{
	for (vector<int>::iterator iter = l.begin(); iter != l.end(); ++iter)
		cout << *iter << " ";
	cout << endl;
}



int main()
{
	vector<int> a;
	deque<int> b;
	
	for (int i = 1; i <= 9; ++i)
		a.push_back(i);
	for (int i = 12; i <= 23; ++i)
		b.push_back(i);
	print(a);
	for (deque<int>::iterator iter = b.begin(); iter != b.end(); ++iter)
		cout << *iter << " ";
	cout << endl;
    deque<int>::iterator pos;
	pos=swap_ranges(a.begin(), a.end(), b.begin());//只能交换九个
	print(a);
	for (deque<int>::iterator iter = b.begin(); iter != b.end(); ++iter)
		cout << *iter << " ";
	cout << endl;
	if (pos != b.end())
	{
		cout << "第一个没有交换的数:" << *pos << endl;
	}
	//swep——range可以把一部分进行交换
	swap_ranges(b.begin(), b.begin() + 3, b.rbegin());//前三位和最后三位交换
	for (deque<int>::iterator iter = b.begin(); iter != b.end(); ++iter)
		cout << *iter << " ";
	cout << endl;

	vector<int> c;
	vector<int> d;

	c.push_back(1);
	c.push_back(2);
	c.push_back(3);

	d.push_back(10);
	d.push_back(20);
	d.push_back(30);
	c = d;//赋值很慢,要把数据移除,一个一个赋值。

	c.swap(d);//很快,内部优化的交换,只是交换了指针,所以很快
	cout << c.at(0) <<" "<< c.at(1)<<" " << c.at(2) << endl;

	system("pause");
	return 0;
}