C++ vector容器元素排序

32 篇文章 0 订阅

merge、sort、random_shuffle、reverse 

#include<iostream>
#include<vector>
#include<algorithm>
#include<functional>
#include<ctime>
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<int> v1;
	vector<int> v2;
	for (int i = 1; i <= 10; i++) {
		v1.push_back(i);
		v2.push_back(i * 2);
	}

	vector<int> 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() {
	vector<int>v2;
	for (int i = 1; i <= 10; i++)
	{
		v2.push_back(i);
	}

	sort(v2.begin(),v2.end(),greater<int>());
	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() {
	vector<int>v3;
	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() {
	vector<int>v4;
	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
请按任意键继续. . .

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值