扩展代码,
#include <algorithm>
#include <iostream>
#include <string>
#include <vector>
using namespace std;
struct Record {
string name;
// ... other fields ...
bool operator<(const Record& other) const { return name < other.name; }
friend ostream& operator<<(ostream& os, const Record& record) {
os << record.name; // Assuming that "name" is the only field to be printed
return os;
}
};
auto rec_eq = [](const Record& r1, const Record& r2) { return r1.name < r2.name; }; // compare names
void f(const vector<Record>& v) {
auto er = equal_range(v.begin(), v.end(), Record{"Reg"}, rec_eq);
for (auto p = er.first; p != er.second; ++p) {
cout << *p << ' '; // assuming that "<<" is defined for Record
}
}
int main() {
vector<Record> records = {{"Alice"}, {"Bob"}, {"Charlie"}, {"Dave"}, {"Eve"}, {"Reg"}, {"Reg"}, {"Reg"}};
// Assume that the vector "records" is sorted based on the "name" field
f(records);
return 0;
}
这里主要是对 equal_range 的理解,这里传入给 equal_range 的 vector 必须是有序的,不管是升序还是降序,这个升序还是降序可以在 rec_eq 中体现。