c++用vector先按学生的年级排序,再按学生的分数排序算法

// VectorSort.cpp : 定义控制台应用程序的入口点。
//

#include "stdafx.h"
#include "stdio.h"
#include "string.h"
#include <vector>

using namespace std;

struct Stu
{
	std::string name;
	int level;
	int score;
};

int _tmain(int argc, _TCHAR* argv[])
{
	vector<Stu> stuVec;
	for (size_t i = 0; i < 6; i++)
	{
		Stu stu;
		stu.name = "vvv";
		stu.level = i*2;
		stu.score = i * 20;
		stuVec.insert(stuVec.end(), stu);
	}

	Stu stu1;
	stu1.name = "vvv";
	stu1.level = 4;
	stu1.score = 500;
	stuVec.insert(stuVec.end(), stu1);

	Stu stu2;
	stu2.name = "vvv";
	stu2.level = 4;
	stu2.score = 7;
	stuVec.insert(stuVec.end(), stu2);

	Stu stu3;
	stu3.name = "vvv";
	stu3.level = 5;
	stu3.score = 500;
	stuVec.insert(stuVec.end(), stu3);

	Stu stu4;
	stu4.name = "vvv";
	stu4.level = 4;
	stu4.score = 30;
	stuVec.insert(stuVec.end(), stu4);

	Stu stu5;
	stu5.name = "vvv";
	stu5.level = 7;
	stu5.score = 80;
	stuVec.insert(stuVec.end(), stu5);

	vector<Stu>::iterator it;
	vector<Stu>::iterator it2;
	for (it = stuVec.begin(); it != stuVec.end(); it++)
	{
		printf("stu %d %d \n", it->level, it->score);
	}

	printf("\n");

	for (it = stuVec.begin(); it != stuVec.end(); it++)
	{
		for (it2 = it + 1; it2 != stuVec.end(); it2++)
		{
			Stu temp;
			if (it ->level > it2->level) {
				temp = *it;
				*it = *it2;
				*it2 = temp;
			}

			if (it->level == it2->level) {
				if (it->score > it2->score) {
					temp = *it;
					*it = *it2;
					*it2 = temp;
				}
			}
		}
	}

	for (it = stuVec.begin(); it != stuVec.end(); it++)
	{
		printf("stu %d %d \n", it->level, it->score);
	}

	printf("\n");


	getchar();
	return 0;
}


猜你喜欢

转载自blog.csdn.net/u013654125/article/details/79769763