C++ map容器

简单来说,map就是由键值对构成的集合,它以键key从小到大排键值对,可以遍历也可以按数组的方式进行访问,用起来很便利

创建map

使用时需要包含头文件

#include <map>

创建的方式为 map <keyType, valType> m,其中key和val分别为键、值,类型为任意基本类型

map <int, string> m1;
map <string, string> m2;

添加键值对的两种方式:

m[key] = value;
m.insert(pair<keyType, valType>(key, val));

举例:

#include<bits/stdc++.h>
using namespace std;

int main()
{
    
    
	map <int, string> m;	//根据key值对键值对排序
	m[2] = "c";
	m[0] = "a";
	m.insert(pair<int, string>(1, "b"));
	return 0;
}


map的基本操作

map的基本操作函数

函数 功能
begin() 返回指向map头部的迭代器
rend() 返回指向map头部的第一个逆向迭代器
end() 返回指向map尾部的迭代器
clear() 清空map中的元素
empty() 若map为空则返回True
size() 返回当前map中的元素个数
max_size() 返回map的最大容纳量

迭代器
1、创建迭代器:

map <keyType, valType> :: iterator it;		//创建正向迭代器
map <keyType, valType> :: reverse_iterator rit;		//创建反向迭代器

注意:同一类型的map共用同一个迭代器

2、map的begin()、end()、rbegin()和rend()所指向的位置如下,
在这里插入图片描述

元素的遍历
遍历分为正向遍历和反响遍历
正向遍历使用 it+begin()+end();反向遍历使用 rit+rbegin()+rend();

	map <int, string> m;		//创建
	m[2] = "c";
	m[0] = "a";
	m[1] = "b";
	
	map <int, string> :: iterator it;			//正向遍历
	for (it=m.begin(); it!=m.end(); it++)
		cout << it->first << " -> " << (*it).second << endl;
	
	map <int, string> :: reverse_iterator rit;	//反向遍历
	for (rit=m.rbegin(); rit!=m.rend(); rit++)
		cout << rit->first << " -> " << rit->second << endl;

查找
find(key) 函数返回一个迭代器,指向被查找的元素key,未找到时返回map尾部的迭代器

map <keyType, valType> m;
map <keyType, valType> :: iterator it;
it = m.find(key);
if (it == m.end())
	cout << "Not find";
else
	cout << "The value is" << it->second << endl;

删除
erase(it) 函数用于删除迭代器指向的键值对

it = m.find(key);
if (it != m.end())
	m.erase(it);

swap函数
swap()函数可以交换两个容器

map <int, int> m1, m2;
m1.swap(m2);


多项式相加

【问题描述】一个多项式可以表示为一组数对,数对中第一个数始终为整数,且唯一,表示多项式的次数,另一数表示为对应的系数且不为0。输入两组数对,每组以0 0作为结束,实现对两个多项式的加法并按降幂输出结果数对

【输入形式】每行输入一个数对,以空格为分隔符,以0 0结束

【输出形式】每行输出一个数对,以空格为分隔符

【样例输出】
0 5
2 4
0 0
0 -2
2 -4
1 1
0 0
【样例输出】
1 1
0 3

源代码

#include <bits/stdc++.h>
using namespace std;

int main()
{
    
    
	map <int, int> m;
	int a, b;
	int count = 2;
	while(count--){
    
    
		while(true){
    
    
			cin >> a >> b;
			if (b == 0)
				break;
			else
				m[a] += b;
		}
	}
	
	map <int, int> :: reverse_iterator rit;
	for (rit=m.rbegin(); rit!=m.rend(); rit++)
		cout << rit->first << " " << rit->second << endl;
		
	return 0;
}

猜你喜欢

转载自blog.csdn.net/qq_41140138/article/details/100619691