【C++】比较器的实现,使用lambda

代码

lambda表达

[](const Student& a, const Student& b) {return a.m_id < b.m_id; }
//2021/05/11H:\笔试题\左神算法课\左神算法课.vcxproj
#include <iostream>
#include <string>
#include <vector>
#include <algorithm>
using namespace std;

class Student
{

public:
	Student(){}
	Student(string name, int id, int age) {
		this->m_name = name;
		this->m_id = id;
		this->m_age = age;
	}

public:
	static void printStudents(vector<Student> students) {
		for (int i = 0; i < 3; i++) {
			cout << "Name : " << students[i].m_name << ", Id : "
				<< students[i].m_id << ", Age : " + students[i].m_age << endl;
		}
	}

public:
	string m_name;
	int m_id;
	int m_age;
};



bool cmp(const Student& a, const Student& b)
{
	return a.m_id < b.m_id;
}

auto f = [](const string& a, const string& b) {
	return a.size() < b.size(); };

void testFunc1()
{
	Student students[3];
	students[0] = { "A", 2, 23 };
	students[1] = { "B", 3, 21 };
	students[2] = { "C", 1, 22 };
	vector<Student> v;
	v.push_back(students[0]);
	v.push_back(students[1]);
	v.push_back(students[2]);
	Student::printStudents(v);

	//sort(v.begin(), v.end(), cmp);
	sort(v.begin(), v.end(), [](const Student& a, const Student& b) {
		return a.m_id < b.m_id; });
	//sort(v, v.begin(), v.end());

	Student::printStudents(v);

}



int main()
{

	testFunc1();

	cout << "hello world!" << endl;
	system("pause");
	return 0;
}
上一篇:21分钟 MySQL 入门教程


下一篇:SQL语句(基础)