c++可变序列算法

可变序列算法:就是能改变容器内容的算法。

copy(first1,last1,first2)

复制容器元素

#include<iostream>
#include<vector>
#include<algorithm>
using namespace std;
void main()
{
	vector<int>a;
	vector<int>b(5);
	a.push_back (4);
	a.push_back (7);
	a.push_back (2);
	a.push_back (5);
	a.push_back (8);
	copy(a.begin (),a.end (),b.begin () );			//copy data
	for(int i=0;i<a.size();i++)
	{
		cout<<a[i]<<"  ";
	}
	cout<<endl;
	for(int j=0;j<b.size();j++)
	{
		cout<<b[j]<<"  ";
	}
	cout<<endl;
	system("pause");
}

fill(first,last,data)

把irst和list的范围内的值都变成值data

#include<iostream>
#include<vector>
#include<algorithm>
using namespace std;
void main()
{
	vector<int>a;
	a.push_back (4);
	a.push_back (7);
	a.push_back (2);
	a.push_back (5);
	a.push_back (3);
	for(int i=0;i<a.size();i++)
	{
		cout<<a[i]<<"  ";
	}
	cout<<endl;
	fill(a.begin (),a.begin ()+3,9 );		//fill element
	for(int j=0;j<a.size();j++)
	{
		cout<<a[j]<<"  ";
	}
	cout<<endl;
	system("pause");
}
swap(a,b)

交换两个容器的元素

#include<iostream>
#include<vector>
#include<algorithm>
using namespace std;
void func(int i)
{
	cout<<i<<"  ";
}
void main()
{
	vector<int>a;
	vector<int>b;
	a.push_back (4);
	a.push_back (7);
	a.push_back (2);
	a.push_back (5);
	a.push_back (3);
	b.push_back (33);
	b.push_back (54);
	b.push_back (84);
	b.push_back (63);
	b.push_back (46);
	cout<<"a:";
	for_each(a.begin(),a.end(),func);
	cout<<endl<<"b:";
	for_each(b.begin(),b.end (),func);
	cout<<endl<<"a:";
	swap(a,b);				//exchange data
	for_each(a.begin (),a.end (),func);
	cout<<endl<<"b:";
	for_each(b.begin (),b.end (),func);
	system("pause");
}
reverse(first,last)

颠倒first和last范围内元素的顺序

#include<iostream>
#include<vector>
#include<algorithm>
using namespace std;
void main()
{
	vector<int>a;
	a.push_back (4);
	a.push_back (7);
	a.push_back (2);
	a.push_back (5);
	a.push_back (3);
	for(int i=0;i<a.size();i++)
	{
		cout<<a[i]<<"  ";
	}
	cout<<endl;
	reverse(a.begin (),a.end () );			//reverse order
	for(int j=0;j<a.size();j++)
	{
		cout<<a[j]<<"  ";
	}
	system("pause");
}


阅读更多
上一篇c++非可变序列算法
下一篇c++排序算法
想对作者说点什么? 我来说一句

没有更多推荐了,返回首页

关闭
关闭