map定义时的两种方式(比较大小)以及equal_range

#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;
}

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值