C++ vector容器元素排序

C++ vector容器元素排序,第1张

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
请按任意键继续. . .

欢迎分享,转载请注明来源:内存溢出

原文地址: https://outofmemory.cn/zaji/5698565.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-12-17
下一篇 2022-12-17

发表评论

登录后才能评论

评论列表(0条)

保存