C++ 结构体多元素sort排序调用时的写法

方法1:用std::bind

例如:

#include <iostream>
#include <algorithm>
#include <functional>

using namespace std;
using std::placeholders::_1;
using std::placeholders::_2;

struct BeSortClass
{
   
	int value = 0;
};

class TestClass
{
   
private:
	BeSortClass b[5];
	int c[5] = {
    3, 22, 5, 100, 8 };
public:
	TestClass()
	{
   
		for (int i = 0; i < 5; i++)
		{
   
			b[i].value = i;
		}
	}

	bool cmp(BeSortClass b1, BeSortClass b2)
	{
   
		return b1.value > b2.value;//从大到小排序
	}

	//bool cmp(int b1, int b2)
	//{
   
	// return b1 <b2;//从小到大排序
	//}

	void test() {
   
		auto bound_cmp = bind(&TestClass::cmp, this, _1, _2);
		sort(b, b + 5, bound_cmp);
		for (int i = 0; i < 5; ++i)
		{
   
			cout << b[i].value << endl;
		}
		//sort(c, c + 5, bound_cmp);
		//for (int i = 0; i < 5; ++i) 
		//{
   
		// cout << c[i] << endl;
		//}
	}
};

int main() {
   
	TestClass testa;
	testa.test();
	system("pause");
	return 0;
}

方法2:声明比较类

struct Less
{
   
    bool operator()(const Student& s1, const Student& s2)
    {
   
        return s1.name < s2.name; //从小到大排序
    }
};
 
std::sort(sutVector.begin(), stuVector.end(), Less());

例如:

#include <iostream>
#include<algorithm>
using namespace std;
typedef struct {
   
	unsigned int x;
	unsigned int y;
	float value;
}structTest;
class SortTest
{
   
public:
	SortTest() {
   }
	void run()
	{
   
		test();
	}
private:
	void test();

	struct Sort
	{
   
		bool operator() ( structTest left, structTest right)
		{
   
			return left.value<right.value;
		}
	};
};

void SortTest::test()
{
   
	structTest *test = new structTest[10];


	for (int i = 0; i < 10; i++) {
   
		test[i].value = 10-i;
		test[i].x = i;
		test[i].y = 10 + i;
	}

	std::sort(test, test+10, Sort());

	for (int i = 0; i<10; ++i)
	{
   
		cout << test[i].value<<"\t"<< test[i]. x<< "\t" << test[i]. y<<endl;
	}
}

int main()
{
   
	SortTest test;
	test.run();
	system("pause");
	return 0;
}

方法3:声明外部比较函数

bool Less(const Student& s1, const Student& s2)
{
   
    return s1.name < s2.name; //从小到大排序
}
std::sort(sutVector.begin(), stuVector.end(), Less);

注意:比较函数必须写在类外部(全局区域)或声明为静态函数
(注意:这里的compare函数是全局函数,而不是成员函数。)
当comp作为类的成员函数时,默认拥有一个this指针,这样和sort函数所需要使用的排序函数类型不一样,会出现错误。

方法4:重载类的比较运算符

bool operator<(const Student& s1, const Student& s2)
{
   
    return s1.name < s2.name; //从小到大排序
}
std::sort(sutVector.begin(), stuVector.end());