STL——常用排序算法

avatar
作者
猴君
阅读量:0

 1.sort()

 

void MyPrint(int val) { 	cout << val << " "; } void test01() { 	vector<int> v1; 	v1.push_back(10); 	v1.push_back(20); 	v1.push_back(40); 	v1.push_back(30); 	v1.push_back(20); 	v1.push_back(40); 	v1.push_back(50); 	sort(v1.begin(), v1.end(), greater<int>());//用内建函数模板实现降序 	for_each(v1.begin(), v1.end(), MyPrint); 	cout << endl; }

2.random_shuffle()//随机打乱顺序

void MyPrint(int val) { 	cout << val << " "; } void test01() { 	vector<int> v1; 	srand((unsigned int)time(NULL));//随机数种子 	for (int i = 0; i < 10; i++) 	{ 		v1.push_back(i); 	} 	for_each(v1.begin(), v1.end(), MyPrint); 	cout << endl; 	cout << "随机打乱顺序后" << endl; 	random_shuffle(v1.begin(), v1.end());//随机打乱顺序 	for_each(v1.begin(), v1.end(), MyPrint); 	cout << endl; }

 3.merge()//归并

 

void MyPrint(int val) { 	cout << val << " "; } void test01() { 	vector<int> v1; 	vector<int> v2; 	for (int i = 0; i < 10; i++) 	{ 		v1.push_back(i); 		v2.push_back(i + 1); 	} 	vector<int> v3; 	v3.resize(v1.size() + v2.size());//归并前必须先开辟空间 	merge(v1.begin(), v1.end(), v2.begin(), v2.end(), v3.begin());//必须是有序且升序 	for_each(v3.begin(), v3.end(), MyPrint); 	cout << endl; }

4.reverse()//反转

void MyPrint(int val) { 	cout << val << " "; } void test01() { 	vector<int> v1; 	for (int i = 0; i < 10; i++) 	{ 		v1.push_back(i); 	} 	cout << "反转前:" << endl; 	for_each(v1.begin(), v1.end(), MyPrint); 	cout << endl; 	reverse(v1.begin(), v1.end());//实现反转 	cout << "反转后:" << endl; 	for_each(v1.begin(), v1.end(), MyPrint); 	cout << endl; }

广告一刻

为您即时展示最新活动产品广告消息,让您随时掌握产品活动新动态!