C/C++教程

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

本文主要是介绍【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;
}
这篇关于【C++】比较器的实现,使用lambda的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!