C++ STL(6):Map

Map:

描述:Map 是 C++ 的一种映射容器,每个元素拥有一个 key 值,和一个对于的映射 map 值,而且没有两个 map 拥有相同的 key 值,意味着 Map 是一种一对多的映射容器。

示例:

代码:

#include <iostream>
#include <cstdlib>
#include <cstdio>
#include <map>
#include <iterator>
using namespace std;

int main() {
	// 定义 map 容器,初始为空
	map<int , int>container;

	// 插入元素
	container.insert(pair<int , int>(1 , 10));
	container.insert(pair<int , int>(2 , 20));
	container.insert(pair<int , int>(3 , 30));
	container.insert(pair<int , int>(4 , 40));
	container.insert(pair<int , int>(5 , 40));
	container.insert(pair<int , int>(6 , 50));
	container.insert(pair<int , int>(7 , 60));
	container.insert(pair<int , int>(8 , 80));
	container.insert(pair<int , int>(9 , 90));
	container.insert(pair<int , int>(10 , 100));

	// 打印 map
	// 定义迭代指针
	map<int , int>::iterator itr;
	cout<<"The Map container is :"<<endl;
	for(itr = container.begin(); itr != container.end(); ++itr) {
		cout<<"key : " << itr -> first << " value : " << itr -> second<<endl;
	}

	// 删除 key = 4 的映射
	cout<<endl<<"removed key = 4 : container.erase(4);" <<endl;
	container.erase(4);
	for(itr = container.begin(); itr != container.end(); ++itr) {
		cout<<"key : " << itr -> first << " value : " << itr -> second<<endl;
	}

	// 输出 key = 3 的 value 值
	cout<<endl<<"print key = 3 : cout<<container[3];" <<endl;
	cout<<"container[3] :" << container[3]<<endl;

	// 利用 lower bound 查找 container 中 key = 5
	cout<<endl<<"lower_bond search key = 5 : " <<endl;
	cout<<container.lower_bound(5) -> first <<" "<<container.lower_bound(5) -> second<<endl;
	return 0;
}

输出:

The Map container is :
key : 1 value : 10
key : 2 value : 20
key : 3 value : 30
key : 4 value : 40
key : 5 value : 40
key : 6 value : 50
key : 7 value : 60
key : 8 value : 80
key : 9 value : 90
key : 10 value : 100

removed key = 4 : container.erase(4);
key : 1 value : 10
key : 2 value : 20
key : 3 value : 30
key : 5 value : 40
key : 6 value : 50
key : 7 value : 60
key : 8 value : 80
key : 9 value : 90
key : 10 value : 100

print key = 3 : cout<<container[3];
container[3] :30

lower_bond search key = 5 : 
5 40

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值