map

map_第1张图片

// map.cpp: 定义控制台应用程序的入口点。
//

#include "stdafx.h"

#include
#include
using namespace std;
void test01()
{
	map<int, int> m;
	m.insert(pair<int, int>(1, 10));
	m.insert(make_pair(2, 20));
	m.insert(map<int, int>::value_type(3, 30));
	m[4] = 40;//如果保证key存在 可以通过[]访问
	for (map<int, int>::iterator it = m.begin(); it != m.end(); it++)
	{
		cout << "key" << it->first << "  value=" << it->second << " " << endl;
	}
	m[5];
	for (map<int, int>::iterator it = m.begin(); it != m.end(); it++)
	{
		cout << "key" << it->first << "  value=" << it->second << " " << endl;
	}
	//10 20 30 40  0
	
	cout << "----"<<m[4] << endl;//40
}
void test2()
{
	map<int, int> m;
	m.insert(pair<int, int>(1, 10));
	m.insert(make_pair(2, 20));
	m.insert(map<int, int>::value_type(3, 30));
	m[4] = 40;

	m.erase(1);//删除key为1的
	for (map<int, int>::iterator it = m.begin(); it != m.end(); it++)
	{
		cout << "key" << it->first << "  value=" << it->second << " " << endl;
	}

	map<int, int>::iterator pos = m.find(2);
	if (pos == m.end())
	{
		cout << "没找到" << endl;
	}
	else {
		cout << "找到了" << pos->first<<"   "<<pos->second << endl;
	}

	int num=m.count(3);//0 或1 
	cout << "key为3的有" << num << "个" << endl;

	//lower_bound(keyElem)返回key>=keyElem的第一个元素
	map<int, int>::iterator ret = m.lower_bound(3);
	if (ret == m.end())
	{
		cout << "没有大于等于" << 3 << "的元素" << endl;
	}
	else {
		cout << "大于等于3的第一个元素为" << ret->second << endl;
	}
	//upper_bound(keyElem)返回key>keyElem的第一个元素

	map<int, int>::iterator ret1 = m.upper_bound(3);
	if (ret1 == m.end())
	{
		cout << "没有大于" << 3 << "的元素" << endl;
	}
	else {
		cout << "大于3的第一个元素为" << ret1->second << endl;
	}
//	equal_range
	pair<map<int, int>::iterator, map<int, int>::iterator> ret2 = m.equal_range(3);
	if (ret2.first != m.end())//ret2.first   迭代器
	{
		cout << "找到了equal_range中的lower_bound的key" << ret2.first->second << endl;
	}
	else {
		cout << "没找到equal_range中的lower_bound的key" << endl;
	}

	if (ret2.second != m.end())
	{
		cout << "找到了equal_range中的upper_bound的key" << ret2.second->second << endl;
	}
	else {
		cout << "没找到equal_range中的upper_bound的key" << endl;
	}

}
//指定排序规则
class myCompare {
public:
	bool operator()(int v1,int v2) 
	{
		return v1 > v2;
	}
};
void test3()
{
	map<int, int> m;
	m.insert(pair<int, int>(1, 10));
	m.insert(make_pair(2, 20));
	m.insert(map<int, int>::value_type(3, 30));
	m[4] = 40;
	//从大到小排序
	for (map<int, int, myCompare>::iterator it = m.begin(); it != m.end(); it++)
	{
		cout << "key  " << it->first << "value" << it->second << endl;
	}

}
int main()
{
	test3();
    return 0;
}


你可能感兴趣的:(c++)