STL之sort 排序

说明:

下面程序给出了如何对自定义结构的特殊排序,主要利用STL中的sort排序算法完成。

#include "stdafx.h"
#include <string.h>
#include <algorithm>
#include <vector>
#include <deque>
#include <functional>
#include <iostream>
#include <list>
#include <sstream>
#include <iterator>
#include <functional>

using namespace std;


struct tagStudent
{
	string strName;
	int nAge;
};

//自定义谓词函数进行比较
//每个比较条件,均需使用“<”,否则程序异常
bool lessLength(const tagStudent &a, const tagStudent& b)
{
	if (a.nAge == b.nAge)
	{
		//姓名长度相等,则按照字典排序
		if (a.strName.length() == b.strName.length())
		{
			return a.strName < b.strName;
		}
		else
		{
			return a.strName.length() < b.strName.length();	
		}
	}
	else
	{
		return a.nAge < b.nAge;
	}
}

//使用function中的函数,进行比较,只能重载<
//每个比较条件,均需使用“<”,否则程序异常
bool operator< (const tagStudent &a, const tagStudent& b)
{
	if (a.nAge == b.nAge)
	{
		return a.strName < b.strName;//字典排序
	}
	else
	{
		return a.nAge < b.nAge;
	}
}

int _tmain(int argc, _TCHAR* argv[])
{

	stringstream ss;
    //字符串流含义:姓名 年龄 姓名 年龄
	string str = "Abel 10 Ruby 15 Jin 10 Dave 15 Botton 35 Jone 35";
	string strWord;
	struct tagStudent stTemp;
	vector<tagStudent> vecStudentInfos;

	ss.clear();
	ss.str(str);
	//提取字符串码流中的信息
	while (ss >> strWord)
	{
		stTemp.strName = strWord;
		strWord.clear();
		ss >> strWord;
		stTemp.nAge = atoi(strWord.c_str());

		vecStudentInfos.push_back(stTemp);
 	}
	
	cout << "sort before:" << endl;
	vector<tagStudent>::iterator it = vecStudentInfos.begin();
	for (; it != vecStudentInfos.end(); ++it)
	{
		cout << "(" <<it->strName << "," << it->nAge <<")" << endl;
	}
	
	//方法一:重载<
	cout << "sort after by dictionary:" << endl;
	sort(vecStudentInfos.begin(), vecStudentInfos.end(), less<tagStudent>());
	for (it = vecStudentInfos.begin(); it != vecStudentInfos.end(); ++it)
	{
		cout << "(" <<it->strName << "," << it->nAge <<")" << endl;
	}

	//方法二:谓词函数
	cout << "sort after by string length:" << endl;
	sort(vecStudentInfos.begin(), vecStudentInfos.end(), lessLength);

	for (it = vecStudentInfos.begin(); it != vecStudentInfos.end(); ++it)
	{
		cout << "(" <<it->strName << "," << it->nAge <<")" << endl;
	}

	return 0;
}


原文地址:https://www.cnblogs.com/jinxiang1224/p/8468432.html