首页 > 代码库 > stl中常用的排序算法

stl中常用的排序算法

#include"iostream"
#include"vector"
using namespace std;
#include"string"
#include"algorithm"

void main_mergr()
{
	vector<int > v1;
	v1.push_back(1);
	v1.push_back(2);
	v1.push_back(3);

	vector<int > v2;
	v2.push_back(1);
	v2.push_back(6);
	v2.push_back(8);

	vector<int > v3;
	v3.resize(v1.size() + v2.size());//这一步还挺重要的的呢
	// 合并两个有序序列,存放到另一个序列。无序则出错。
	merge(v1.begin(), v1.end(), v2.begin(), v2.end(), v3.begin());

	for (vector<int>::iterator it = v3.begin(); it != v3.end(); it++)
	{
		cout << *it << " ";
	}
}  
////////////////////////////////////////////////////////////////////////
class Teacher
{
public:
	Teacher(int age, string name)
	{
		m_age = age;
		m_name = name;
	}
	void printT()
	{
		cout << "name: " << m_name << " m_age " << m_age << endl;
	}
protected:
public:
	int m_age;
	string m_name;
};
bool Compare(Teacher & tem1, Teacher &tem2)
{
	return (tem1.m_age > tem2.m_age);
}
void main_sort()
{	
	Teacher t1(1, "dsd"), t2(3, "dsfsd"), t3(13, "dfsdd");
	vector<Teacher> tem;
	tem.push_back(t1);
	tem.push_back(t2);
	tem.push_back(t3);
	//以默认升序的方式重新排列指定范围内的元素。若要改排序规则,可以输入比较函数。
	sort(tem.begin(), tem.end(), Compare);
	
	for (vector<Teacher>::iterator it = tem.begin(); it != tem.end(); it++)
	{
		it->printT();
	}
}
/////////////////////////////////////////////////
void main_random_shuffle()
{
	vector<int > v1;
	v1.push_back(1);
	v1.push_back(9);
	v1.push_back(3);
	random_shuffle(v1.begin(), v1.end());//对指定范围内的元素随机调整次序
	for (vector<int>::iterator it = v1.begin(); it != v1.end(); it++)
	{
		cout << *it << " ";
	}
	cout << endl;
	reverse(v1.begin(), v1.end());//让序列逆序
	for (vector<int>::iterator it = v1.begin(); it != v1.end(); it++)
	{
		cout << *it << " ";
	}
}
int main()
{
	main_mergr();
	cout << endl;
	main_sort();
	main_random_shuffle();
	system("pause");
}

  

stl中常用的排序算法