priority_queue
#include <iostream>
#include <queue>
#include <vector>
struct Compare {
bool operator()(const int& a, const int& b) const {
return a > b;
}
};
int main() {
std::priority_queue<int, std::vector<int>, Compare> pq;
pq.push(3);
pq.push(1);
pq.push(5);
while (!pq.empty()) {
std::cout << pq.top() << " ";
pq.pop();
}
std::cout << std::endl;
return 0;
}
std::sort
#include <iostream>
#include <vector>
#include <algorithm>
class Person {
public:
int id;
std::string name;
Person(int id, const std::string& name) : id(id), name(name) {}
};
bool compareById(const Person& p1, const Person& p2) {
return p1.id < p2.id;
}
int main() {
std::vector<Person> people = {Person(2, "Alice"), Person(1, "Bob"), Person(3, "Charlie")};
std::sort(people.begin(), people.end(), compareById);
for (const auto& person : people) {
std::cout << "id: " << person.id << ", name: " << person.name << std::endl;
}
return 0;
}
使用函数对象
#include <iostream>
#include <vector>
#include <algorithm>
class Person {
public:
int id;
std::string name;
Person(int id, const std::string& name) : id(id), name(name) {}
};
struct CompareById {
bool operator()(const Person& p1, const Person& p2) const {
return p1.id < p2.id;
}
};
int main() {
std::vector<Person> people = {Person(2, "Alice"), Person(1, "Bob"), Person(3, "Charlie")};
std::sort(people.begin(), people.end(), CompareById());
for (const auto& person : people) {
std::cout << "id: " << person.id << ", name: " << person.name << std::endl;
}
return 0;
}