#include <iostream>
#include <map>
#include <algorithm>
using namespace std;
class MyKey {
public:
MyKey(int index, int id) : mIndex(index), mID(id){}
方法一:直接在自定义类中重载< ,此方式定义map时格式为map<MyKey, int> mymap;
//bool operator< (const MyKey &other) const {
// return mID < other.mID;
//}
public:
int mIndex;
int mID;
};
方法二: 自定义比较大小的类,此方式定义map时格式为map<MyKey, int, mycompair> mymap;
class mycompair { // functor for operator<
public:
bool operator()(const MyKey& _Left, const MyKey& _Right) const { // apply operator< to operands
return _Left.mID < _Right.mID;
}
};
void test02() {
map<MyKey, int, mycompair> mymap;
mymap.insert(make_pair(MyKey(1, 111), 11));
mymap.insert(make_pair(MyKey(1, 2), 12));
mymap.insert(make_pair(MyKey(1, 33), 13));
mymap.insert(make_pair(MyKey(1, 4), 14));
for (map<MyKey, int>::iterator it = mymap.begin(); it != mymap.end(); it++) {
cout << (*it).first.mID << endl;
}
pair<map<MyKey, int, mycompair>::iterator, map<MyKey, int, mycompair>::iterator> ret =
mymap.equal_range(MyKey(1, 33));
if (ret.first != mymap.end()) {
cout << "lower_bound yes" << endl;
}
else
{
cout << "lower_bound no" << endl;
}
if (ret.second != mymap.end()) {
cout << "upper_bound yes" << endl;
}
else
{
cout << "upper_bound no" << endl;
}
}
int main() {
test02();
return 0;
}
map定义时的两种方式(比较大小)以及equal_range
于 2023-05-24 11:46:16 首次发布