栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > C/C++/C#

C++ vector容器元素排序

C/C++/C# 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

C++ vector容器元素排序

merge、sort、random_shuffle、reverse 

#include
#include
#include
#include
#include
using namespace std;

class myCompareClass {
public:
	bool operator()(int v1,int v2)const
	{	
		return v1 > v2;
	}
};

bool myCompareFunction(int v1,int v2) {
	return v1 < v2;
}

//merge合并两个容器
void test01() {
	vector v1;
	vector v2;
	for (int i = 1; i <= 10; i++) {
		v1.push_back(i);
		v2.push_back(i * 2);
	}

	vector target;
	target.resize(v1.size()+v2.size());
	//v1,v2必须有序
	merge(v1.begin(), v1.end(), v2.begin(), v2.end(), target.begin());

	for_each(target.begin(), target.end(), [](int val) {cout << val << " "; });
	cout << endl;
}

//sort排序
void test02() {
	vectorv2;
	for (int i = 1; i <= 10; i++)
	{
		v2.push_back(i);
	}

	sort(v2.begin(),v2.end(),greater());
	for_each(v2.begin(), v2.end(), [](int val) {cout << val << " "; });
	cout << endl;

	sort(v2.begin(),v2.end(),myCompareFunction);
	for_each(v2.begin(), v2.end(), [](int val) {cout << val << " "; });
	cout << endl;

	sort(v2.begin(), v2.end(), myCompareClass());
	for_each(v2.begin(), v2.end(), [](int val) {cout << val << " "; });
	cout << endl;
}

//random_shuffle对指定范围内的元素随机调整次序
void test03() {
	vectorv3;
	for (int i = 1; i <= 10; i++)
	{
		v3.push_back(i);
	}

	random_shuffle(v3.begin(), v3.end());
	for_each(v3.begin(), v3.end(), [](int val) {cout << val << " "; });
	cout << endl;
}

//reverse反转指定范围的元素
void test04() {
	vectorv4;
	for (int i = 1; i <= 10; i++)
	{
		v4.push_back(i);
	}

	cout << "反转前:";
	for_each(v4.begin(), v4.end(), [](int val) {cout << val << " "; });
	cout << endl;

	reverse(v4.begin(), v4.end());

	cout << "反转后:" ;
	for_each(v4.begin(), v4.end(), [](int val) {cout << val << " "; });
	cout << endl;
}

int main() {
	test01();
	cout << "----------------------------" << endl;
	test02();
	cout << "----------------------------" << endl;
	test03();
	cout << "----------------------------" << endl;
	test04();
	system("pause");
	return EXIT_SUCCESS;
}
1 2 2 3 4 4 5 6 6 7 8 8 9 10 10 12 14 16 18 20
----------------------------
10 9 8 7 6 5 4 3 2 1
1 2 3 4 5 6 7 8 9 10
10 9 8 7 6 5 4 3 2 1
----------------------------
9 2 10 3 1 6 8 4 5 7
----------------------------
反转前:1 2 3 4 5 6 7 8 9 10
反转后:10 9 8 7 6 5 4 3 2 1
请按任意键继续. . .

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/698434.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号